Roci
Roci

Reputation: 123

Initialize static field in abstract class at run time

I need to initialize a field that will be accessed from many instances of a class. The initialization requires some computation, and there will be millions of instances, so I need the initialization to only happen once, and for the variable to be shared between all instances to save memory. Finally, I would like to make this happen in an abstract class.

How would I initialize the static variable my_val calculated by CalculateMyVal() at run time?

abstract class MyAbstract
{
    static readonly int my_val;
    int CalculateMyVal()
    {
        int x = 1;
        // Long Calculation on x
        return x;
    }
}

Upvotes: 2

Views: 280

Answers (1)

Akash KC
Akash KC

Reputation: 16310

You can use static constructor if you want to initialize your static variable :

    public abstract class MyAbstract
    {
        static readonly int my_val;
        static MyAbstract()
        {
            my_val = CalculateMyVal();
        }

        static int CalculateMyVal()
        {
            int x = 1;
            // Long Calculation on x
            return x;
        }
    }

Upvotes: 5

Related Questions