Consider the following class:
public class MyClass
{
public static string[] SomeAmazingConsts = { Const1 };
public static string Const1 = "Constant 1";
public static string Const2 = "Constant 2";
}
Now, check out the usage:
class Program
{
static void Main(string[] args)
{
string[] s = MyClass.SomeAmazingConsts;
//s[0] == null
}
}
The problem is that s[0] == null! How the heck does this happen? Now, reorder the static variable of MyClass as follows:
public class MyClass
{
public static string Const1 = "Constant 1";
public static string Const2 = "Constant 2";
public static string[] SomeAmazingConsts = { Const1 };
}
Things start to work properly. Anyone can shed some light on this?
A static class is basically the same as a non-static class, but there is one difference: a static class cannot be instantiated. In other words, you cannot use the new operator to create a variable of the class type.
In Java, the static keyword is primarily used for memory management. We can use the static keyword with variables, methods, blocks, and classes. Using the static class is a way of grouping classes together. It is also used to access the primitive member of the enclosing class through the object reference.
In C#, a static class is a class that cannot be instantiated. The main purpose of using static classes in C# is to provide blueprints of its inherited classes. Static classes are created using the static keyword in C# and . NET.
In C#, one is allowed to create a static class, by using static keyword. A static class can only contain static data members, static methods, and a static constructor.It is not allowed to create objects of the static class. Static classes are sealed, means you cannot inherit a static class from another class.
From 10.4.5.1 Static field initialization
The static field variable initializers of a class correspond to a sequence of assignments that are executed in the textual order in which they appear in the class declaration.
So the initialization happens top to bottom, and in the first case Const1
has not been initialized, hence the null
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With