CSharp - Write program to use this keyword to reference instance variable

Requirements

Create two objects of the same class but the instance variable (i) is initialized with different values.

To do this job, we have used a parameterized constructor that can accept one integer argument.

Hint

Demo

using System;

class ClassA/*from ww  w.  j a v  a2  s  .co  m*/
{
    public int i;
    public ClassA(int i)
    {
        this.i = i;
    }
}

class Program
{
    static void Main(string[] args)
    {
        ClassA obA = new ClassA(10);
        ClassA obB = new ClassA(20);
        Console.WriteLine("obA.i =" + obA.i);
        Console.WriteLine("obB.i =" + obB.i);
        Console.ReadKey();
    }
}

Result

What is the purpose of this?

To refer the current object, we use the "this" keyword.

In the example, instead of using the "this" keyword, we could write code like the following to achieve the same result.

class ClassA
{
    int i;//instance variable 
    ClassA(int myInteger)//myInteger is a local variable here 
    {
        i = myInteger;
    }
}