Betamoo
Betamoo

Reputation: 15870

C# memory allocation

Thanks

Upvotes: 3

Views: 1484

Answers (4)

Brian Rasmussen
Brian Rasmussen

Reputation: 116401

If new fails it will throw OutOfMemoryException. Additionally the constructor itself may throw any exception depending on the implementation.

From the MSDN documentation for OutOfMemoryException:

The following Microsoft intermediate (MSIL) instructions throw OutOfMemoryException :

  • box

  • newarr

  • newobj

Upvotes: 9

Marc Gravell
Marc Gravell

Reputation: 1062780

A new operator that invokes a constructor can throw any exception that you can imagine. Fro example, if inside the constructor it tries to allocate something big and fails, then that exception might be caught and re-raised as something more exotic.

Of course, at the point when you start seeing out-of-memory you should probably consider the process terminally ill, and put it out of its misery ASAP.

Constructors can also, despite all the rumours to the contrary, return null even for classes - but that is an extreme edge-case, bordering on the pathological.

Upvotes: 4

Svetlozar Angelov
Svetlozar Angelov

Reputation: 21660

Yes, it throws OutOfMemoryException

Upvotes: 1

Eric Lippert
Eric Lippert

Reputation: 660058

Does using operator new in c# might fail (if it requires a large memory)?

Yes. (The resource you are likely to run out of is address space, not memory per se.)

And how to discover it?

I don't understand the question.

Upvotes: 1

Related Questions