Conversation


Your input fuels progress! Share your tips or experiences on prioritizing mental wellness at work. Let's inspire change together!

Join the discussion and share your insights now!

Comments 0


"this" Keyword in c#

this keyword in c#


"This" keyword is used to refer to the current object of the class. It is used to resolve conflicts between variables having the same names and to pass the current object as a parameter. You cannot use this keyword with static variables and methods. 

Example 1:

class person
{
     private string name;
     public person(string name)
     { 
           //use the "this" keyword to set the local variable
            this.name = name;
     }
     public void introduceyourself()
     {
           Console.WriteLine("Hello, My name is " + this.name);
           Console.ReadKey();
     }
}

class Program
{
      static void Main(string[] args)
      {
            person personobj = new person("TEXVN");
            personobj.introduceyourself();
      }
}

Output:-
Hello, My name is TEXVN


Example 2:

class myclass
{
      private int num;
      public myclass(int num)
      {
               //Use the "this" keyword to disambiguate between the parameter

                and the class feild
                this.num = num;
       }
       public void displaynum()
       {
                //Use the "This" keyword to access the class number
                Console.WriteLine("Number Value: " + this.num);
                Console.ReadKey();
       }
}

class program
{
        static void Main(string[] args)
        { 
                 myclass myclassobj = new myclass(60);
                 myclassobj.displaynum();
        }
}

Output:-
Number Value: 60


C# this keyword this keyword in c# c# this keyword in static method c# this keyword in parameter This keyword in C# constructor
Blogs