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.
Structs are allocated on the stack, if a local function variable, or on the heap as part of a class if a class member.
Are struct instances sometimes allocated on the heap? Yes, they are sometimes allocated on the heap.
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.
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.
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?
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With