In C++, we usually see and write code like,
Sample sample=new Sample();
if ( sample == NULL )
{
std::cout<<"Memory allocation failed" << std::endl;
}
But in C#, I rarely see this: (at least I've never seen this)
Sample sample = new Sample();
if ( sample == null )
{
Console.WriteLine("Memory allocation failed\n");
}
Means, in C#, we rarely check if a new
failed or not. Why is it so? Does it have something to do with "In C#, new never fails"? Is there such a thing in C# that new
never fails?
If it fails, then why such "check" is so rare in C#? I'm not talking about OutOfMemoryException
, that is after all exception, not "check". I'm talking about the coding style.
According to msdn
If the new operator fails to allocate memory, it throws the exception OutOfMemoryException.
http://msdn.microsoft.com/en-us/library/51y09td4%28v=vs.71%29.aspx
By the way, only old C++ compilers return 0 when they trying to allocate memory. Modern ones throwing std::bad_alloc exception. If you wish old behavior you need to write
Sample sample=new(std::nothrow) Sample();
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