Night Walker
Night Walker

Reputation: 21280

check for null after object creation

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.

Upvotes: 6

Views: 2038

Answers (5)

BoltClock
BoltClock

Reputation: 723708

The new operator serves to allocate memory for a new instance of a class. Instantiating using new can, in "normal" scenarios (see Marc's answer for an edge case), never result in null, assuming memory is allocated successfully.

If object creation fails because its constructor threw an exception or memory can't be allocated, the code after that statement won't execute. So even if the object was null and you tried to check, the check doesn't happen. You would handle the exception instead using a try-catch block.

Upvotes: 3

Marc Gravell
Marc Gravell

Reputation: 1062865

It really depends on how much you need to guard against pathologically stupid code ;p The following new() (against a class) will return null:

MyFunnyType obj = new MyFunnyType();

with:

class MyFunnyProxyAttribute : System.Runtime.Remoting.Proxies.ProxyAttribute {
   public override MarshalByRefObject CreateInstance(Type serverType) {
      return null;
   }
}
[MyFunnyProxy]
class MyFunnyType : ContextBoundObject { }

You do, thankfully, need to go a long way off-piste to get this type of crazy, though. In any sane code, new() will never return a null (except for Nullable<T>). Both these counter-cases are discussed more here.

But to reiterate: no, don't check the result for null unless you have reason to suspect somebody is being really, really daft.

Upvotes: 11

David Neale
David Neale

Reputation: 17028

No, there is no point checking this.

Upvotes: 1

aroth
aroth

Reputation: 54806

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!)
}

Upvotes: 11

Unknown
Unknown

Reputation: 411

Skip the null check - the only case the object will not be created is the exception in constructor.

Upvotes: 0

Related Questions