C# this Keyword
The this Keyword
The this keyword refers to the current object: the object that a constructor or method belongs to.
In the Constructors chapter, the constructor parameter and the field had different names (modelName and model). Many programmers give them the same name, because they describe the same thing. But then C# needs a way to tell them apart.
Look at this constructor. Both the field and the parameter are called model:
Example
class Car
{
public string model;
public Car(string model)
{
model = model;
}
}
class Program
{
static void Main(string[] args)
{
Car myCar = new Car("Mustang");
Console.WriteLine("Model: " + myCar.model);
}
}
The output is Model: , with no model name. Why?
Inside the constructor, model means the parameter, not the field. So model = model; only gives the parameter its own value. The field is never set, and stays empty.
Use this to Refer to a Field
To refer to the field, write this. in front of it:
Example
class Car
{
public string model;
public Car(string model)
{
this.model = model;
}
}
class Program
{
static void Main(string[] args)
{
Car myCar = new Car("Mustang");
Console.WriteLine("Model: " + myCar.model);
}
}
this.model is the field of the current object. model is the parameter.
With more fields, use this for each of them:
Example
class Car
{
public string model;
public string color;
public int year;
public Car(string model, string color, int year)
{
this.model = model;
this.color = color;
this.year = year;
}
}
class Program
{
static void Main(string[] args)
{
Car myCar = new Car("Mustang", "Red", 1969);
Console.WriteLine(myCar.color + " " + myCar.year + " " + myCar.model);
}
}
Call Another Constructor
A class can have more than one constructor, with different parameters. One constructor can call another one with : this(...). This way, you write the code that sets the fields only once:
Example
class Car
{
public string model;
public int year;
public Car(string model, int year)
{
this.model = model;
this.year = year;
}
public Car(string model) : this(model, 2020)
{
}
}
class Program
{
static void Main(string[] args)
{
Car car1 = new Car("Mustang", 1969);
Car car2 = new Car("Astra");
Console.WriteLine(car1.model + " " + car1.year);
Console.WriteLine(car2.model + " " + car2.year);
}
}
new Car("Astra") uses the second constructor. It passes the model and the year 2020 on to the first constructor, which sets both fields.
The second constructor has an empty body { }, because the first constructor does all the work.