I understand this topic is answered a lot. My question is specific to the way it is said or asked.
So am I right to say, that code written with a class keyword will be on the managed heap and is a reference type, and code that is written with a struct will be on stack and is a value type?
I used to think like this as well. However, I recently had a nice discussion with Jon Skeet (he may provide more details) and he explained me that a
value typemay be kept on the heap as well. The key is how long will that variable be used. If it’s a short-lived value type variable, it will be left only at the stack. However, if it’s used many times, the framework will keep it at the heap to save space at the stack.IMO, the key difference between reference and value types relies on passing the object to another object or method. If it’s a reference type, you are simply sharing its reference. If it’s a value type, then you are making a copy of it.
About the subject of short x long-lived variable, here is the full picture:
Source: The Truth About Value Types (it’s also on the comments)