Check null after creating an object

I create a new object

myobject t = new myobject();

should i check the next line for null reference if new succeeded?

if (null != t)

or I'm sure that this object will certainly be different from zero ...

Thank.

+5
source share
5 answers

According to the documentation in C # , if newit was not possible to allocate space for an instance of a new object, it will be thrown away OutOfMemoryException, so there is no need to do an explicit check for null.

If you are trying to detect cases where newit was not possible to select a new object, you can 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!)
}
+11
source

, ; p new() ( ) null:

MyFunnyType obj = new MyFunnyType();

:

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

, , , . new() null ( Nullable<T>). .

: , null, , - , .

+10

new . new "" (. "" ) , , .

If the creation of the object failed because its constructor threw an exception or memory cannot be allocated, the code after this statement will not be executed. Therefore, even if the object was null and you tried to verify it, the verification does not occur. Instead, you should handle the exception using a try-catch block.

+3
source

No, there is no point in checking this.

+1
source

Skipping null checking is the only case where an object will not be created is an exception in the constructor.

0
source

All Articles