you can get and set static properties in a static class in a C# program. Note that to use a static property with a backing store field, you must also specify that the backing store be static. The program does not demonstrate this use. The program shows the automatically implemented property syntax in the static bool property.
using System;
static class Settings
{
public static int DayNumber
{
get
{
return DateTime.Today.Day;
}
}
public static string DayName
{
get
{
return DateTime.Today.DayOfWeek.ToString();
}
}
public static bool Finished
{
get;
set;
}
}
class Program
{
static void Main()
{
//
// Read the static properties.
//
Console.WriteLine(Settings.DayNumber);
Console.WriteLine(Settings.DayName);
//
// Change the value of the static bool property.
//
Settings.Finished = true;
Console.WriteLine(Settings.Finished);
}
}
Out put:
13
Sunday
True
Using static properties: Defines a compilation unit that includes two classes. The Settings class is decorated with the static modifier and it cannot be instantiated because of this. It has three static properties; two of the static properties are read-only and only have the get accessor, while the third is writable as well.
Static classes. In the C# programming language, static classes have a restriction that they cannot be instantiated. This means you are much less likely to needlessly create an instance of class that has no state. Static properties are a good function type to put inside a static class. Many projects use a global variable class that often can be expressed as a static class with static properties. Static properties can be accessed with the composite name, using the dot notation.
Concept of global variables in programming languages generally and the C# language in specific. Global variables are very useful and even functional languages use global environments for binding variables and function names. However, in practical use global variables can increase complexity and cognitive footprint. This can be dealt with by using accessor routines, as noted in the specific article.
Thread-safety issues. Usually, threading problems will only occur if the values are being written to by at least one thread. Using static properties that are readonly is very safe in practice; because the memory is only being read, there is no chance for it to be written at the wrong time. One strategy for reducing threading problems is to initialize the values at startup of the application or website, and then treat them as read-only.