CodeBlanks Logo Icon CodeBlanks

The this keyword

C# course · Intermediate · Lesson 4/116

Learn to reference the class itself with this.

What is this?

The this keyword refers to the current instance. Its most common use is to distinguish a field from a parameter that shares the same name: this.name = name;.

Here this.name refers to the class field, while name refers to the method parameter. Without this, name = name assigns the parameter to itself; the field stays unchanged. That is why this is essential in shadowing situations.

Why this qualification matters

When a parameter shares the field's name, the compiler prefers the parameter. In name = name; both sides refer to the parameter; the field never changes. This is a silent bug and the code still compiles.

The this prefix tells the compiler that the left side is the class field, so the assignment works correctly. Rule: when parameter and field share a name, always use this. You can also avoid this entirely by choosing different names.

Exercise Use this in the Student class

The Student class already has private string name;. Add a public void SetName(string name) method with this.name = name; in the body. Also add a public string GetName() method with return name;. Inside Main call SetName("Alex") and print with GetName().

Show example solution
In SetName write this.name = name;. In GetName write return name;. In Main add s.SetName("Alex"); Console.WriteLine(s.GetName());.
Example solution:
using System;

class Student
{
    private string name;

    public void SetName(string name)
    {
        this.name = name;
    }

    public string GetName()
    {
        return name;
    }
}

class Program
{
    static void Main()
    {
        Student s = new Student();
        s.SetName("Alex");
        Console.WriteLine(s.GetName());
    }
}

Test yourself

  1. What does this.name = name; do?

    public void SetName(string name) { this.name = name; }
    • Assigns the parameter name to the class field name
    • Declares a new local variable
    • Ignores the parameter
    • Resets the class
    Show answer

    Assigns the parameter name to the class field name — Correct. this.name is the field, name is the parameter.

  2. Complete the assignment with this

    public void SetName(string name) { this.name = ____; }
    Show answer
    public void SetName(string name) { this.name = name; }
  3. Match each this usage to its purpose

    this.name = name
    Separate field from parameter
    this
    Current instance
    this.Greet()
    Call own method
    name = name
    Self assignment (no-op)

All lessons in Intermediate