Reference Types

Reference Types

In C# there are two different kinds of types, there is the reference types and the value types. A reference type doesn’t contain the actual data but contains a pointer to a memory space that holds the data. Two variables of reference type can point to the same object each can change the object referenced by the other variable. A value type actually holds the data and if a new value type variable is created, then a copy of the data is made.

C# provides the reference types of dynamic, object, and string.

As you can see from the below code, on a reference type the variables can be changed because they are pointers to a memory space and don’t hold the data values like a value type.

   public class ClassValueType
    {
        public int testVariable;
    }
    class Program
    {
        static void Main(string[] args)
        {

            ClassValueType originalClass = new ClassValueType();
            originalClass.testVariable = 123; // assign the initial value

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

            ClassValueType newClassValue = originalClass; // create a new copy of the struct
            newClassValue.testVariable = 456; // assign 456 to the new struct.

            Console.WriteLine(originalClass.testVariable);  //456 will be printed
            Console.WriteLine(newClassValue.testVariable); //456 will be printed

            newClassValue = originalClass;
            Console.WriteLine(newClassValue.testVariable); //456 will be printed

            Console.Read();

        }
    }