I am curious to know that could it be possible that in the below code static Instance is not null but the MYDB class reference gets disposed by GAC and set to null ?
public class DA_Setting
{
private static readonly DA_Setting instance = new DA_Setting();
public static DA_Setting Instance
{
get { return instance; }
}
db MYDB = new db();
// Some other methods here
private void Getname()
{
MYDB.GetNames(); // Sometimes this line throws null reference error on LIVE server.
}
}
The GC will never, ever set something to
null. Period.If you have a reference to an object, the GC is designed to see that you’re still using the object, holding onto it by that reference, and therefore won’t collect it until you’re done with it.
The only way for the
MYDBfield to benullis if you fail to assign a value to it (and I can see you have an initializer in your code that prevents that scenario), or if you assign a value ofnullto the field at some later point in your code.I would suggest you turn
MYDBinto a get-only property and initialize it in your class constructor:This ensures you can’t set this value from outside your class and should give you a much more predictable type to work with.