Identity versus Equivalence


Reference and value types support different memory models. References refer to objects created on the managed heap, whereas value types are created on the stack. Equivalence and identity complement the memory model. Equivalence is the value or state of an instance. Related instances that have the same value are equivalent. Identity is the location of an object.

Equivalent values are related types that contain the same value. In the following code, integers locala and localc are equivalent. However, the variables are not identical because they are stored at different locations on the stack. The variables locala and localb are neither equivalent no identical. They have differenet values and are stored at different locations on the stack:

 int locala=5; int localb=10; int localc=5; 

Assigning a value type copies the value. The target and source are equivalent after this assignment, but not identical:

 locala=localb; // locala and localb are equivalent. 

For reference types, there is synchronicity of equivalence and identity. Related references containing the same value are equivalent and identical. Assigning a reference creates an alias, which can create unplanned side affects. For this reason, be careful when assigning references. The following code has some unplanned side effects:

 using System; namespace Donis.CSharpBook{     public class XInt {         public int iField=0;     }     public class Starter{         public static void Main(){             XInt obj1=new XInt();             obj1.iField=5;             XInt obj2=new XInt();             obj2.iField=10;             // Alias created and second instance lost             obj2=obj1;             obj1.iField=15; // side affect             Console.WriteLine("{0}", obj2.iField); // 15         }     } } 




Programming Microsoft Visual C# 2005(c) The Language
Microsoft Visual Basic 2005 BASICS
ISBN: 0619267208
EAN: 2147483647
Year: 2007
Pages: 161

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net