Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are static fields or properties initialized once?

With the code below, will each call to Test.someBaseField or Test.someBaseProperty result in the function being called and a new instance of SomeBase being created? or does that only happen once at the start?

How would I set it up for the latter (called once at the start)?

public class SomeBase {}
public class SomeObjectA : SomeBase {}
public class SomeObjectB : SomeBase {}

public class Test
{
    public static bool someBool = true;

    public static SomeBase someBaseField = GetBase(someBool);
    public static SomeBase someBaseProperty { get { return GetBase(someBool); } }

    public static SomeBase GetBase(bool getA)
    {
        if(getA)
            return new SomeObjectA() as SomeBase;       
        else
            return new SomeObjectB() as SomeBase;
    }
}
like image 235
user2994682 Avatar asked Apr 07 '26 19:04

user2994682


1 Answers

Get base will be called each time for either property and a new instance of somebase will be returned every time. What you have going on there is called a factory.

What you are wanting to do is create a singleton. There are many methods to create singletons but the most popular is to track some field or property and return that every time if initialized or initialize it if not.

so you are looking at doing something like:

static someBase _trackingVar;
public static someBase someProperty{ 
    get
    {
        if(_trackingVar == null){
            _trackingVar = GetBase(...);
        }
        return _trackingVar;
    }
}

The one problem with this approach is that it is not thread safe. There's a thread safe version of this approach to singleton creation. See http://msdn.microsoft.com/en-us/library/ff650316.aspx for more details

like image 163
Louis Avatar answered Apr 10 '26 11:04

Louis



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!