naveed
naveed

Reputation: 45

Why C# allows initializing static class variables in non-static contructor?

Why C# allows initializing static class variables in non-static contructor? The static variables should only be allowed to be initialized on static constructors. Any ideas?

 public class customer
{
    public string Name;

    public customer()
    {
        Name = "C1";
        Console.WriteLine("creating customer " + Name);
    }

}

class Program
{
    public static customer cust;

    public Program()
    {
        cust = new customer(); //Why is this allowed i.e. initialize a static variable in non-static constructor?
    }

    static void Main(string[] args)
    {
        Program program = new Program();
        program = new Program();

        Console.Read();
    }
}

Upvotes: 4

Views: 8949

Answers (4)

Mike Christensen
Mike Christensen

Reputation: 91598

The short answer is there is no reason why not to allow this. Static variables can be reached anywhere from within the class (and outside, if they're public) and the constructor is no exception. This includes changing their value, or initializing them to a new value.

There are, in fact, several patterns that can take advantage of this behavior. For example, initializing a static object the first time a class is instantiated (perhaps for caching properties that are expensive to initialize but don't change in the future). Another use might be incrementing a counter to keep track of how many of these objects are alive.

With that said, you'd want to be aware of static objects in a class before initializing, and check to see if they're null before overwriting their values.

Upvotes: 4

Khan
Khan

Reputation: 18142

Don't look at it as initializing, look at it as setting.

If you would only like it to be initialized via a static constructor or at declaration, add the readonly keyword.

E.g.

public readonly static customer cust;

//Allowed
static Program()
{
    cust = new customer(); 
}

//Not Allowed
public Program()
{
    cust = new customer();
}

Upvotes: 13

Egg
Egg

Reputation: 2056

You can access and modify a static variable from any nonstatic function, it will just overwrite the value each time it is called. The opposite is not true, though - static functions can't access nonstatic variables.

Upvotes: 2

Kevin DiTraglia
Kevin DiTraglia

Reputation: 26058

It just means that the static variable is reset every time a new object is initialized. A bit weird, but the compiler allows it.

Upvotes: 0

Related Questions