简体   繁体   中英

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.

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

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.

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.

不,没有必要检查一下。

跳过空检查 - 唯一不创建对象的情况是构造函数中的异常。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM