check for null after object creation

2020-04-06 01:38发布

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.

标签: c# .net
5条回答
Ridiculous、
2楼-- · 2020-04-06 01:49

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

查看更多
做个烂人
3楼-- · 2020-04-06 01:52

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.

查看更多
▲ chillily
4楼-- · 2020-04-06 01:57

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.

查看更多
forever°为你锁心
5楼-- · 2020-04-06 01:57

No, there is no point checking this.

查看更多
闹够了就滚
6楼-- · 2020-04-06 02:05

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!)
}
查看更多
登录 后发表回答