الأربعاء، 17 ديسمبر 2008

Comparing the Behavior of Reference and Value Types

What Is a Reference Type?

Reference types store the address of their data, also known as a pointer, on the stack. The actual data that address refers to is stored in an area of memory called the heap. The runtime manages the memory used by the heap through a process called garbage collection. Garbage collection recovers memory periodically as needed by disposing of items that are no longer referenced.

Comparing the Behavior of Reference and Value Types

Because reference types represent the address of data rather than the data itself, assigning one reference variable to another doesn’t copy the data. Instead, assigning a reference variable to another instance merely creates a second copy of the reference, which refers to the same memory location on the heap as the original variable.

Consider the following simple structure declaration:

class Program

    {

        static void Main(string[] args)

        {

            Numbers n1 = new Numbers(0);

            Numbers n2 = n1;

            n1.val += 1;

            n2.val += 2;

            Console.WriteLine("n1={0},n2={1}", n1, n2);

        }

    }

    struct Numbers

    {

        public int val;

        public Numbers(int _val)

        { val = _val; }

        public override string ToString()

        { return val.ToString(); }

    }  

This code would display “n1 = 1, n2 = 2” because a structure is a value type, and copying a value type results in two distinct values. However, if you change the Numbers type declaration from a structure to a class, the same application would display “n1 = 3, n2 = 3”.

 Changing Numbers from a structure to a class causes it to be a reference type rather than a value type. When you modify a reference type, you modify all copies of that reference type.

Identify Types as Value or Reference

   SByte a = 0;

            Byte b = 0;

            Int16 c = 0;

            Int32 d = 0;

            Int64 e = 0;

            string s = "";

            Exception ex = new Exception();

            object[] array_types ={ a, b, c, d, e, s, ex };

            foreach (object o in array_types)

            {

                string type;

                if (o.GetType().IsValueType)

                    type = "Value Type";

                else

                    type = "Refrence Type";

                Console.WriteLine("{0}:{1}", o.GetType(), type);

            }

0 التعليقات: