C# this Keyword

In c#, this keyword is used to refer the current instance of class and by using this keyword we can pass current instance of class as a parameter to the other methods.

 

In case, if class contains a parameters and variables with same name, then this keyword is useful to distinguish between the parameters and variables.

 

We can also use this keyword to declare indexers and to specify the instance variable in the parameter list of an extension method.

 

In c#, we should not use this keyword to refer static field or method and also it cannot used in static classes.

C# this Keyword Syntax

Following is the syntax of using this keyword in c# programming language.

 

this.instance_variable

If you observe above syntax, this is a keyword and instance_variable is an instance variable name.

C# this keyword Example

Following is the example of using this keyword in c# programming language to refer the class variables and parameters of same name and use this keyword to send instance of class to the method of another class.

 

using System;

 

namespace Tutlane

{

    class User

    {

        public string name, location;

        public long marks = 470;

        public User(string name, string location)

        {

            // Use this to distinguish between parameters and variables

            this.name = name;

            this.location = location;

        }

        public void GetUserDetails()

        {

            Console.WriteLine("Name: {0}", name);

            Console.WriteLine("Location: {0}", location);

            // Passing a class instance to the method using this

            Console.WriteLine("Marks: {0}", Exams.GetPercentage(this));

        }

    }

    class Exams

    {

        public static double GetPercentage(User u)

        {

            double i = ((double)470 / 600) * 100;

            return (i);

        }

    }

 

    class Program

    {

        static void Main(string[] args)

        {

            User u = new User("Suresh Dasari", "Hyderabad");

            u.GetUserDetails();

            Console.WriteLine("\nPress Enter Key to Exit..");

            Console.ReadLine();

        }

    }

}

If you observe above example, we used this keyword to distinguish between class variables and parameters of same name and used this keyword to send instance of class (User) to the method of another class.

 

When we run above c# program, we will get the result like as shown below.

 

C# this keyword Example Result

 

This is how we can use this keyword in c# programming language to refer the instance of class based on our requirements.

Topics Covered