Value types in use
suggest changeValue types simply contain a value.
All value types are derived from the System.ValueType class, and this includes most of the built in types.
A local value type is stored in an area of memory called the stack. A value type that is a field of a class is stored inside that object on the heap, not on the stack.
The storage is the size of the declared type. An int is always 32 bits. When a local value type goes out of scope, its stack slot is released.
The code below demonstrates a value type being assigned to a new variable. A struct is being used as a convenient way to create a custom value type (the System.ValueType class cannot be otherwise extended).
When you assign a value type, the value itself is copied. You then have two independent values. Changing one does not change the other. ReferenceEquals boxes both arguments, so it is the wrong tool for comparing value-type identity; the name change below is the real demonstration.
struct PersonAsValueType
{
public string Name;
}
class Program
{
static void Main()
{
PersonAsValueType personA;
personA.Name = "Bob";
var personB = personA;
personA.Name = "Linda";
Console.WriteLine( // Outputs 'False' - because
object.ReferenceEquals( // personA and personB are referencing
personA, // different areas of memory
personB));
Console.WriteLine(personA.Name); // Outputs 'Linda'
Console.WriteLine(personB.Name); // Outputs 'Bob'
}
}