use of this keyword in c#

 

# this keyword :-


1. In C#  “this” keyword is used to refer to the current instance of the class.


    class Test

    { 

        int num;

        Test(int num)

        {

            // this.num refers to the instance field

            this.num = num;

            Console.WriteLine("object of this: " + this);

        }

 

        static void Main(string[] args)

        { 

            Test t1 = new Test(4);

            Console.WriteLine("object of t1: " + t1);

            Console.ReadLine();

        }

    }


2. It is also used to differentiate between the method parameters and class fields if they both have the same name.


public class Employee

{

    private int id;

    private string name;

 

    public Employee(int id, string name)

    {

        this.id = id;

        this.name = name;

    }

}

3. Using ‘this’ keyword to invoke current class method.


class Test

{ 

    void display()

    {

        // calling function show()

        this.show(); 

        Console.WriteLine("Inside display function");

    } 

    void show()

    {

        Console.WriteLine("Inside show function");

    } 

    // Main Method

    public static void Main(String[] args)

    {

        Test t1 = new Test();

        t1.display();

    }

}


4. Using this() to invoke the constructor in same class.


    class Test

    { 

        Test(int num1, int num2)

        { 

            Console.WriteLine("Constructor with two parameter");

        }

 

        // invokes the constructor with 2 parameters

        Test(int num) : this(33, 22)

        { 

            Console.WriteLine("Constructor with one parameter");

        }

 

        public static void Main(String[] args)

        { 

            Test t1 = new Test(11);

            Console.ReadLine();

        }

     }



   


 


 


No comments:

Post a Comment