Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Would simple class instantiation ever fail in C#?

I saw some code written by another developer that looks something like this:

var stringBuilder = new StringBuilder();

if(stringBuilder == null)
{
    // Log memory allocation error
    // ...
    return;
}

(It is ALL over the place in the code )

Question 1: Would that error logging code even get called? If there was no memory, wouldn't an System.OutOfMemoryException be thrown on that first line?

Question 2: Can a call to a constructor ever return null?

like image 590
John B Avatar asked Jul 19 '10 18:07

John B


2 Answers

You're correct, and that code is wrong. It will throw OutOfMemoryException on a failure. This is clear in the documentation:

"If the new operator fails to allocate memory, it throws the exception OutOfMemoryException."

Constructors don't return anything, let alone null. They manipulate an object that's already been allocated.

like image 74
Matthew Flaschen Avatar answered Nov 15 '22 22:11

Matthew Flaschen


My assumption is that the coder used to work in C++, and doesn't know how things work in C#.

like image 32
James Curran Avatar answered Nov 15 '22 22:11

James Curran