Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Static variable initialization using new gives a code hazard

I am working on some code which is something like this:

class A
{
   static SomeClass a = new Someclass("asfae");  
}

Someclass contains the required constructor. The code for this compiles fine without any warning. But I get a code hazard in system:

"The Someclass ctor has been called from static constructor and/or static initialiser"

This code hazard part of system just to make it better by warning about possible flaws in the system or if system can get into bad state because of this. I read somewhere on the web that static constructor/initialiser can get into deadlock in c# if they wait for a thread to finish. Does that have something to do with this?

I need to get rid of this warning how can i do this. I can't make the member unstatic as it's used by a static function. What should I do in this case , Need help.

like image 883
grv Avatar asked Nov 11 '22 11:11

grv


1 Answers

You could hide it behind a property and initialize it on first use (not thread-safe);

class A
{
    static SomeClass aField;

    static SomeClass aProperty
    {
        get
        {
           if (aField == null) { aField = new Someclass("asfae"); }
           return aField;
        }
    }
}

or use Lazy (thread-safe):

class A
{
    static Lazy<SomeClass> a = new Lazy<SomeClass>(() => new Someclass("asfae"));
}

...or this very verbose thread safe version :)

class A
{
    static SomeClass aField;

    static object aFieldLock = new object();

    static SomeClass aProperty
    {
        get
        {
           lock (aFieldLock)
           {
               if (aField == null) { aField = new Someclass("asfae"); }
               return aField;
           }
        }
    }
}
like image 157
Jonas Jämtberg Avatar answered Nov 15 '22 11:11

Jonas Jämtberg