Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When do structs not live on the stack?

Tags:

stack

c#

struct

I'm reading through Jon Skeet's book reviews and he is going over the numerous inaccuracies of Head First C#.

One of them caught my eye:

[Under Errors Section] Claiming that structs always live on the stack.

In what situations would structs not live on the stack? This goes contrary to what I thought I knew about structs.

like image 835
mmcdole Avatar asked Feb 10 '09 08:02

mmcdole


People also ask

Are structs stored on the stack?

Structs are allocated on the stack, if a local function variable, or on the heap as part of a class if a class member.

Do structs live on the heap?

Are struct instances sometimes allocated on the heap? Yes, they are sometimes allocated on the heap.

Do structs need to be initialized C#?

Struct initialization and default values All of a struct's member fields must be definitely assigned when it's created because struct types directly store their data. The default value of a struct has definitely assigned all fields to 0.

Does New allocate on stack or heap?

In classical architectures, the stack and heap grow toward each other to maximize the available space. C++ uses the new operator to allocate memory on the heap.


2 Answers

One common example is where the struct is a member of an object that is allocated in the heap. There is lots of additional detail in this question here. What’s the difference between struct and class in .Net?

like image 122
1800 INFORMATION Avatar answered Sep 19 '22 13:09

1800 INFORMATION


Whenever they are a field on a class

Unusual examples of this:

a: When a value-type variable is captured:

int i = 2;
Action action = delegate {i++;}
action();
Console.WriteLine(i);

This is compiled to something more like:

class Foo {
    public int i;
    public void Bar() {i++;}
}
...
Foo foo = new Foo();
foo.i = 2;
Action action = foo.Bar;
action();
Console.WriteLine(foo.i);

b: When a value-type variable is used in an iterator block:

IEnumerable<int> GetValues() {
   for(int i = 0 ; i < 5 ; i++) yield return i;
}

(the compiler generates a state machine to represent the iterator, of which all local variables (such as i) are fields)

like image 26
Marc Gravell Avatar answered Sep 23 '22 13:09

Marc Gravell