.NET Framework Value types in use


Value types simply contain a value.

All value types are derived from the System.ValueType class, and this includes most of the built in types.

When creating a new value type, the an area of memory called the stack is used.
The stack will grow accordingly, by the size the declared type. So for example, an int will always be allocated 32 bits of memory on the stack. When the value type is no longer in scope, the space on the stack will be deallocated.

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).

The important thing to understand is that when assigning a value type, the value itself copied to the new variable, meaning we have two distinct instances of the object, that cannot affect each other.

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

        Console.WriteLine(personA.Name);  // Outputs 'Linda'
        Console.WriteLine(personB.Name);  // Outputs 'Bob'