Value Or Reference? A C# Puzzle |
Written by Balamurugan Boominathan | |||
Page 1 of 2 The difference between a value and a reference type is very clear to most C# programmers, but it can be a shock when a simple piece of code that seems to do exactly what you want has a surprise in store. BackgroundIt is fundamental that an entity can be represented in either value type or reference type. The most important difference in using these types is in updating the object property value of the entity. In case of values type, the actual value will be stored on the stack in the case of a reference type the value is stored on the heap and the variable contains a reference to the value. Example: int a = 10; leaves 10 stored in a because the assignment to b results in a copy of the value in the a variable being made. This means that b doesn't store a reference to the value but a copy of the value itself. Now consider: class Value { In this case a.a will store 100 not 10 because a class is reference type and it will be stored on heap and any variables of the type store a reference to the object on the heap - not the object itself. When b is initialised to a, a copy of the object isn't made. Instead a reference to the object is stored in b and now a and b reference the same object on the heap. So when we make use of any properties via b we are in fact using the properties associated with the object that a refers to as well as b. This much is well known to most C# programmers, but there are times when the way that value types work can surprise you. PuzzleConsider a product entity which has been declared as value type - remember structs are value types: public struct Product You can now create a sophisticated data structure which uses the struct as its element type. For example a generic List can be used to holds details of products: List<Product> lstProducts = lstProducts.Add(new Product Now consider when anyone purchases a product. Its Quantity property should be updated by subtracting the Quantity bought. You might write this in a function something like: bool OrderProduct(String ProductName, This looks perfectly fine C# - but does it work? Turn to the next page when you are ready to find out.
|