Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

check for null after object creation

Tags:

c#

.net

I am creating a new object

myobject t = new myobject();

should I check on the next line for null reference , if the new succeeded ?

if (null != t)

or I can be sure that this object for sure will be different then null ...

Thanks.

like image 761
Night Walker Avatar asked Apr 08 '11 10:04

Night Walker


1 Answers

According to the C# documentation, if new fails to successfully allocate space for a new object instance, an OutOfMemoryException will be thrown. So there's no need to do an explicit check for null.

If you are trying to detect cases where new has failed to allocate a new object, you might want to do something like:

try {
    myobject t = new myobject();
    //do stuff with 't'
}
catch (OutOfMemoryException e) {
    //handle the error (careful, you've run out of heap space!)
}
like image 175
aroth Avatar answered Oct 20 '22 20:10

aroth