Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if a class instance has been created or is null C#

Tags:

c#

class

How do you check if classinstance has been created/initialised or is null?

private MyClass myclass;

if(!check class has been initialised)      //<- What would that check be?
    myclass = new MyClass();

Thanks in advance

like image 594
James Avatar asked Dec 04 '22 03:12

James


1 Answers

Just check if it is null

if (myclass == null)

As mentioned in your comment,

if (myclass.Equals(null)) 

will not work because if myclass is null, that's translated to

if (null.Equals(null))

which leads to a NullReferenceException.

By the way, objects declared in class scope are automatically initialized to null by the compiler, so your line:

private MyClass myclass;

is the same as

private MyClass myclass = null;

Objects declared in a method are forced to be assigned some initial value (even if that initial value is null).

like image 168
Eric J. Avatar answered Jan 06 '23 06:01

Eric J.