Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Strange behavior on static members of a class - How's this possible?

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?

like image 533
Joe Bank Avatar asked Apr 08 '14 03:04

Joe Bank


People also ask

What are static classes?

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.

What is the point of a static class?

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.

What is static class and Why we use it in C#?

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.

How to use static methods in C#?

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.


1 Answers

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

like image 103
Adriaan Stander Avatar answered Sep 29 '22 01:09

Adriaan Stander