CSharp - Data Types Reference types

Introduction

A reference type have two parts: an object and its reference.

The content of a reference-type variable is the reference.

The following code creates a Point class.

class Point { 
   public int X, Y; 
}

Assigning a reference-type variable to another variable copies the reference, not the object itself.

It is like duplicating the key to your room.

You can use multiple variables to refer to the same object. You can have several keys to your room.

In the following code you can see that any operation to p1 affects p2:

Demo

using System;

class Point { //w  ww  . j  ava 2  s  . c  o m
   public int X, Y; 
}

public class MainClass
{
   public static void Main(string[] args)
   {
       Point p1 = new Point();
       p1.X = 1;

       Point p2 = p1;             // Copies p1 reference

       Console.WriteLine (p1.X);  
       Console.WriteLine (p2.X);  

       p1.X = 2;                  // Change p1.X

       Console.WriteLine (p1.X);   
       Console.WriteLine (p2.X);  

   }
}

Result