views:

250

answers:

5

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?

+16  A: 

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.

Matthew Flaschen
+3  A: 

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

James Curran
The code is equally wrong for C++. C++ `new` throws `bad_alloc` when allocation fails, unless you explicitly tell it not to.
Matthew Flaschen
That is exactly what one of the interns said here. I myself haven't touched much C++, and not in a LONG time. Thanks.
SkippyFire
@Matthew: yes -- if you are using Standard C++ (and know what you are doing). Pre-Standard C++ returned null, and clearly the author isn't keeping his skills current.
James Curran
A: 
  1. No. An OutOfMemoryException will be thrown if there isn't enough memory available to allocate an object.
  2. No
thecoop
+2  A: 

Now, this code is a different story:

StringBuilder stringBuilder = null;

try { stringBuilder = new StringBuilder(); } catch(Exception) {}

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

In that case, string builder could (conceivably) be null.

Brian Genisio
Actually, the StringBuilder wouldn't be `null`, it would be uninitialized.
Toby
Actually, it will not even compile. But I think we can all assume Brian meant to write `StringBuilder stringBuilder = null;` instead :)
Brian Gideon
Sorry guys. Fixed the code in the example. Who needs a compiler? I should just write a service that sends my code off to SO to be evaluated :)
Brian Genisio
A: 

Here is a better version of the code. You would have much bigger problems if there is not enough memory to allocate a reference though.

StringBuilder stringBuilder = null;

try {
   stringBuilder = new StringBuilder();
}
catch(OutOfMemoryException) {
   // log memory error
}
Dmitry