Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

struct value types

Tags:

c#

.net

I know that struct is a value type , that means it defined on stack .

But I can do A a = new A(); (A my struct of course). and it defined on heap , and only the reference variable is on stack.

Can you explain me this one please .

like image 549
Night Walker Avatar asked May 27 '26 00:05

Night Walker


2 Answers

Value types are stored on the stack sometimes. It's a complex topic and usually the exact storage of a variable (stack or heap) is irrelevant for programming issues. The real difference between value and reference types lies in their behaviour (for example, value types are always copied by value).

Eric Lippert covers this issue in detail:

  • http://blogs.msdn.com/b/ericlippert/archive/2009/04/27/the-stack-is-an-implementation-detail.aspx
  • http://blogs.msdn.com/b/ericlippert/archive/2009/05/04/the-stack-is-an-implementation-detail-part-two.aspx
  • http://blogs.msdn.com/b/ericlippert/archive/2010/09/30/the-truth-about-value-types.aspx
like image 69
Heinzi Avatar answered May 28 '26 13:05

Heinzi


Where a local variable is stored is an implementation detail.
Simple local variables are usually stored in the CPU-registers and/or the stack.

If they are captured in a closure they'll be rewritten into members in a heap allocated object. That's because the lamda might outlive it's creating functions, and thus the variables it uses must be able to live long enough too.

Unlike in C++ in C# the new does not imply a heap allocation. It's just the syntax for calling a constructor.

And calling new on a value-type doesn't have the semantics of a placement new either. It has the semantics of constructing an instance somewhere and then copying it into the target variable.

In my mental model there are two types of storage:

  1. Local storage that can't outlive the return of the function. This includes stack and registers.
  2. Global storage that lives until it isn't referenced anymore. This is usually the heap. But in run-times that do escape analysis it might be put on the stack if the runtime proves that no references will survive the function.

Your example falls into the first kind of storage since you use a value type.

like image 21
CodesInChaos Avatar answered May 28 '26 13:05

CodesInChaos



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!