user7127000
user7127000

Reputation: 3243

Is it possible to create an instance of a class on the stack?

I know that in C++ you can create an instance of a class on the stack like

MyClass mc = MyClass(8.2);

or on the heap like

MyClass * mc = new MyClass(8.2);

Can you do the same thing in C#? The only way I ever create a class in C# is by newing it.

Upvotes: 1

Views: 1074

Answers (1)

Servy
Servy

Reputation: 203827

No, it's not possible. All instances of all classes are always allocated on the heap.

It is value types, including user defined struct types, that hold values, rather than references to values elsewhere, that can store a value in whatever location that variable happens to store its value in, which may not be the heap.

Upvotes: 3

Related Questions