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.
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.
Skip the null check - the only case the object will not be created is the exception in constructor.
It really depends on how much you need to guard against pathologically stupid code ;p The following
new()
(against a class) will returnnull
:with:
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 anull
(except forNullable<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 usingnew
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.
No, there is no point checking this.
According to the C# documentation, if
new
fails to successfully allocate space for a new object instance, anOutOfMemoryException
will be thrown. So there's no need to do an explicit check fornull
.If you are trying to detect cases where
new
has failed to allocate a new object, you might want to do something like: