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?
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.
My assumption is that the coder used to work in C++, and doesn't know how things work in C#.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With