In Focus

Mistakes In C# Programming By Using Reference Like Value

Developers of C++ and numerous different dialects are acclimated to being responsible for whether the qualities they dole out to factors are essential values or are references to existing articles. In C# programming, notwithstanding, that choice is made by the developer who composed the item, not by the software engineer who instantiates the article and allows it to a variable. This is a typical "gotcha" for those endeavoring to learn C# programming.

On the off chance that you don't know whether the objects you're utilizing are an esteem type or reference type, you could keep running into a few amazements. For instance,

  1. Point point1 = new Point(20, 30);  
  2. Point point2 = point1;  
  3. point2.X = 50;  
  4. Console.WriteLine(point1.X);/20 (does this unexpected you?)  
  5. Console.WriteLine(point2.X);/50  
  6. Pen pen1 = new Pen(Color.Black);  
  7. Pen pen2 = pen1;  
  8. pen2.Color = Color.Blue;  
  9. Console.WriteLine(pen1.Color);/Blue (or does this unexpected you?)  
  10. Console.WriteLine(pen2.Color);/Blue  

As should be obvious, both, Point and Pen, objects were made precisely the same way, yet the estimation of point1 stayed unaltered when another X arrange esteem was doled out to point2, though the estimation of pen1 was adjusted when another shading was allocated to pen2. We can, in this manner, conclude that point1 and point2 each contain their very own duplicate of a Point object, while pen1 and pen2 contain references to a similar Pen object. Be that as it may, how might we realize that without doing this test?

The appropriate response is to take a gander at the meanings of the article types (which you can do without much of a stretch in Visual Studio by putting your cursor over the name of the item type and hitting F12):

  1. open struct Point { ... }/characterizes an "esteem" type  
  2. open class Pen { ... }/characterizes a "reference" type  

As it appears in C# programming, the struct watchword is utilized to characterize an esteem type, while the class catchphrase is utilized to characterize a reference type. For those with a C++ foundation, who may have been lulled into an incorrect feeling that all is well with the world by the numerous similarities among C++ and C# watchwords, this conduct likely comes as an unexpected shock that may make them request assistance from a C# instructional exercise.

In case you rely upon some conduct which varies among esteem and reference types – for example, the capacity to pass an article as a technique parameter and have that strategy change the condition of the item – ensure that you're managing the right sort of item to keep away from C# programming issues.