Value Types

Value Types

All value types are derived from the System.ValueType. Variables that are based on value types directly contain values and holds the data within its own memory allocation. When assigning a value type variable to another value type copies the contained value. A reference type variable contains a pointer to another memory location that holds the real data. Reference type variables are stored in the heap, while value type variables are stored in the stack.

    public struct StructValueType
    {
        public int testVariable;
    }
    class Program
    {
        static void Main(string[] args)
        {
            StructValueType originalStruct = new StructValueType();
            originalStruct.testVariable = 123; // assign the initial value

            Console.WriteLine(originalStruct.testVariable); //123 will print out

            StructValueType newStructValue = originalStruct; // create a new copy of the struct
            newStructValue.testVariable = 456; // assign 456 to the new struct.

            Console.WriteLine(originalStruct.testVariable);  //123 will be printed
            Console.WriteLine(newStructValue.testVariable); //456 will be printed

            newStructValue = originalStruct;
            Console.WriteLine(newStructValue.testVariable); //123 will be printed

            Console.Read();

        }
    }