educative.io

Use of this keyword

using System;

public class Animal

{

public string Name;

public Animal() : this(“Dog”)

{

}

public Animal(string name)

{

Name = name;

}

}

public class ConstructorCallingConstructor

{

public static void Main()

{

  Animal Dog1 = new Animal(); // dog.Name will be set to "Dog" by default.

  Console.WriteLine("Doggo's name is {0}",Dog1.Name);

 

  Animal cat = new Animal("Cat"); // cat.Name is "Cat", the empty constructor is not called

  Console.WriteLine("Cat's name is {0}",cat.Name);

}

}

What is the use of this keyword in this code?


Type your question above this line.

Course: https://www.educative.io/collection/10370001/5709110343368704
Lesson: https://www.educative.io/collection/page/10370001/5709110343368704/5670586499989504

Hello @Muhammad_Shamoon

this keyword in Java has a similar function to the this keyword in Python. It is a reference variable referring to the current object of a method or a constructor. It is basically used to eliminate the confusion between class attributes and parameters with the same name. For instance, if you have a class attribute named Name and the parameter of one of the method of that class also has the same naming convention, this will cause confusion. So to avoid this we use this keyword. Instead of:

public class Example
{
 public string Name;
 
  public Animal(string Name)
  {
    Name = Name;
  }
}

We can do the following:

public class Example
{
 public string Name;
 
  public Animal(string Name)
  {
    this.Name = Name;
  }
}

So to avoid confusion and errors, we made use of this.

Hope this helps!