public class MyClass
{
// private fields
//////////////////////////////////////////////////////////////////////////
public MyClass(string param1, string param2)
{
// do some stuff
}
private static object syncRoot = new Object();
private static volatile MyClass instance = null;
public static MyClass Log
{
get
{
if (instance == null)
{
lock (syncRoot)
{
if (instance == null)
instance = new MyClass();
}
}
return instance;
}
}
private MyClass()
{
// do some stuff
}
public void myFunction(string txt, uint flags)
{
// do some stuff
}
}
This is my class and I use it this way
MyClass.Log.myFunction("some string", flags);
But constantly get that either MyClass is null or MyClass.Log is null when i use this class in other class functions.
What do I do wrong?
In addition to the question here is the error i get:
System.NullReferenceException: Object reference not set to an instance of an object.
at MyNamespace.MyClass..ctor()
at MyNamespace.MyClass.get_Log()
The code you showed looks good.
MyClasscan’t benullas it is a class.Logshouldn’t benulleither, your singleton implementation looks OK.My guess is that the problem is that you are using the parameterless constructor of
MyClass. I guess thatmyFunctionsomehow uses something that is only initialized in the constructor that takes the two parameters.Actually, according to your stack trace the problem is inside the parameterless constructor. I guess you are trying to log something in there, like this :
instance.Log(...);. That won’t work, because at that pointinstanceis stillnull. You should simply useLog(...)instead.