Reference types - CSharp Language Basics

CSharp examples for Language Basics:Data Type

Introduction

A reference type has two parts:

  • an object and
  • the reference to that object.

The content of a reference-type variable is a reference to an object.

Here is the Point type written as a class:

public class Point { public int X, Y; }

Assigning a reference-type variable copies the reference, not the object instance.

This allows multiple variables to refer to the same object.

The following code shows that an operation to p1 affects p2:

Demo Code

using System;/*from  w  w w .  j  av  a 2  s  .  c o m*/
public class Point { public int X, Y; }
class Test
{
   static void Main(){
      Point p1 = new Point();
      p1.X = 7;
      Point p2 = p1;             // Copies p1 reference
      Console.WriteLine (p1.X);  // 7
      Console.WriteLine (p2.X);  // 7
      p1.X = 9;                  // Change p1.X
      Console.WriteLine (p1.X);  // 9
      Console.WriteLine (p2.X);  // 9
   }
}

Result


Related Tutorials