Friday, October 30, 2009

.Net Reference vs. Value types

In .net classes are reference types whereas structs are value types.

What this means is that if you copy a class variable to another class variable it will copy the address only. Because of this after the assignment if you change data in one variable the data change will be noticed in the second variable (which points to the same instance) as well.

Here's a short demo:


namespace referencetest
{

    public struct TestValueType
    {
        public int x;
        public TestValueType(int thevalue)
        {
            x = thevalue;
        }
    }

    public class TestReferenceType
    {
        public int x;
        public TestReferenceType(int thevalue)
        {
            x = thevalue;
        }
    }

    class Program
    {

        static void ValueWithoutRef(TestValueType test)
        {
            test.x = 20;
        }
        static void ReferenceWithoutRef(TestReferenceType test)
        {
            test.x = 20;
        }

        static void Main(string[] args)
        {

            TestValueType valueTypeA = new TestValueType(0);
            TestValueType valueTypeB = valueTypeA;
            //Since A/B is a value types
            //Changes in functions or in one variable do not affect any other copies
            ValueWithoutRef(valueTypeA);
            Console.WriteLine(valueTypeA.x); //output 0
            valueTypeA.x = 10;          
            Console.WriteLine(valueTypeB.x); //output 0




            TestReferenceType referenceTypeA = new TestReferenceType(0);
            TestReferenceType referenceTypeB = referenceTypeA;
            ReferenceWithoutRef(referenceTypeA);
            //Value of A being changed Withtout a ref function
            //Causes value of B to be changed
            //since they point to the same data
            Console.WriteLine(referenceTypeB.x); //output 20



            Console.ReadKey();
        }
    }
}



The output :
0
0
20

No comments:

Post a Comment