Adrien Neveu
Adrien Neveu

Reputation: 827

Initialize variables outside the constructor

I want to create a small static class in C#.

This class only needs a list and a bool.

What's the difference between initializing the list and setting the default value of my bool (false) outside of any methods, like that:

class MyClass
{
    static bool A = true;
    static List<int> B = new List<int>();
}

and initializing them inside a method, like that:

class MyClass
{
    static bool A;
    static List<int> B;

    public static void Initialize()
    {
        A = true;
        B = new List<int>();
    }
}

Upvotes: 0

Views: 1503

Answers (1)

Habib
Habib

Reputation: 223392

In your first approach, fields will be assigned the values on the first reference of your static class.

In your second approach, fields will not be assigned your values until you call your method Initialize. They will be assigned default values.

This would be different case if you have a static constructor with your class like:

class MyClass
{
    public static bool A;
    public static List<int> B;

    static  MyClass()
    {
        A = true;
        B = new List<int>();
    }
}

If you want to initialize public fields then you can use static constructor which will be called automatically when any static members is referenced. (Please note that in this case, your fields would be public)

See: Static Constructor - MSDN

A static constructor is used to initialize any static data, or to perform a particular action that needs to be performed once only. It is called automatically before the first instance is created or any static members are referenced.

Upvotes: 8

Related Questions