An example of difference between reference types and value types - CSharp Language Basics

CSharp examples for Language Basics:Data Type

Description

An example of difference between reference types and value types

Demo Code

using System;/*from  ww w .jav a 2  s. c  o  m*/
class Person
{
   private int age = 0;
   public void SetAge(int newAge)
   {
      age = newAge;
   }
   public int GetAge()
   {
      return age;
   }
}
class ReferenceTester
{
   public static void Main()
   {
      Person p1;
      Person p2;
      p1 = new Person();
      p2 = new Person();
      p1.SetAge(2);
      p2.SetAge(33);
      Console.WriteLine("Julian's age: " + p1.GetAge());
      Console.WriteLine("Deborah's age: " + p2.GetAge());
      p1 = p2;
      Console.WriteLine("Julian's age: " + p1.GetAge());
      Console.WriteLine("Deborah's age: " + p2.GetAge());
      p1.SetAge(10);
      Console.WriteLine("Julian's age: " + p1.GetAge());
      Console.WriteLine("Deborah's age: " + p2.GetAge());
   }
}

Result


Related Tutorials