I have a singleton class that lazy creates its instance when a property is first called (property side effect).
namespace singletontest2
{
using System.Diagnostics;
using MySingleton = Singleton<MyClass>;
public class MyClass
{
private int val = 42;
public MyClass()
{
}
}
public static class Singleton<T> where T : new()
{
private static T t;
public static bool IsNull
{
get
{
return t == null;
}
}
[DebuggerBrowsable(DebuggerBrowsableState.Never)]
public static T Instance
{
get
{
if (t == null)
t = new T();
return t;
}
}
}
class Program
{
static void Main(string[] args)
{
var a = MySingleton.IsNull;
var d = MySingleton.Instance;
}
}
}
If I place a break point in the Instance
property getter and on the var d
line, the t
member will already be initialized when I step into the Instance
getter.
If I move the break point from var d
to the next line, the t
is null when I debug into the Instance
getter.
I was under the impression the DebuggerBrowsable
attribute would prevent this but it seems to not make any difference.
HOWEVER, if I eliminate the using MySingleton = Singleton<MyClass>;
above and call Singleton<MyClass>.Instance;
instead of MySingleton.Instance;
, then the member t
is null when I enter the Instance
getter regardless of DebuggerBrowsable
which is what I want.
Why is the using
directive enabling the debugger to evaluate that property before the code is actually executed?