0

I've been reading a book about C# and came across the topic of storing values in memory. An instance of a reference type is always created on the heap, however a variable’s value lives wherever it’s declared. Only local variables (variables declared within methods [not anonymous]) and method parameters live on the stack.

So my question is - if I declare those structs as such local variables - would they be all put on the stack?

struct A<T> where T : struct { }

struct B<T> where T : class { }

struct C { }

I am simply wondering if the content of a struct can have any influence on where it will be stored in the memory.

Thanks, C# gurus!

trincot
  • 317,000
  • 35
  • 244
  • 286
ebvtrnog
  • 4,167
  • 4
  • 31
  • 59
  • 1
    This is going to be one of those "its more complicated than that" questions, rest assured, you don't need to know how .Net is implemented to use c#. Although, it probably doesn't hurt to be inquisitive. – Jodrell Jul 29 '15 at 16:14
  • 4
    Obligatory 'The Stack Is An Implementation Detail' link: http://blogs.msdn.com/b/ericlippert/archive/2009/04/27/the-stack-is-an-implementation-detail.aspx – Rotem Jul 29 '15 at 16:15
  • 1
    Related: http://stackoverflow.com/questions/1113819/arrays-heap-and-stack-and-value-types (note some comments that correct the answer) – D Stanley Jul 29 '15 at 16:17
  • 1
    And part 2 of this great blog post by Eric Lippert http://blogs.msdn.com/b/ericlippert/archive/2009/05/04/the-stack-is-an-implementation-detail-part-two.aspx – Nikolai Samteladze Jul 29 '15 at 16:18
  • I think the interesting question here is whether `struct` content affects where it is stored. Other than that, where `struct` resides is an implementation detail. It is stack in most cases, but they can be on the heap too (class fields, async blocks, iterator blocks, etc.). You might find this SO discussion interesting too http://stackoverflow.com/questions/815354/why-are-structs-stored-on-the-stack-while-classes-get-stored-on-the-heap-net – Nikolai Samteladze Jul 29 '15 at 16:26

1 Answers1

0

structs go where you tell them to go.

If they are declared as a local variable in a function then they are on the stack. If they are class members then they are inline in the heap memory of the class.

If a struct contains a class then the reference is inlined in the struct just like it was an int or any other member. The thing the class reference points at is on the heap

pm100
  • 48,078
  • 23
  • 82
  • 145