← Back to C# Course | Chapter 6: OOP Basics | Lesson 7 of 7

The this Keyword

The this keyword means 'me, the object I am inside right now'. It is like saying my when you point to your own things and not someone else's.

In this page:

  1. The this Keyword
Syntax
csharp
class ClassName
{
    public type Field;

    public ClassName(type field)
    {
        this.Field = field;   // this = the current object
    }
}

The this Keyword

this refers to the current object instance inside a non-static method or constructor. It's most often used to disambiguate an instance field from a parameter of the same name. this can also be used to call another constructor on the same class.

Note: Use this.fieldName = fieldName; in a constructor when the parameter shares the field's name.

Example: The this Keyword

markup
using System;

class Rectangle
{
    public int Width;
    public int Height;

    public Rectangle(int width, int height)
    {
        this.Width = width;
        this.Height = height;
    }

    public int Area()
    {
        return this.Width * this.Height;
    }
}

class Program
{
    static void Main(string[] args)
    {
        Rectangle r = new Rectangle(4, 5);
        Console.WriteLine(r.Area());
    }
}
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
Common Mistakes
  1. Using this inside a static method, where it is not available.
  2. Naming a parameter the same as a field and forgetting this. when assigning, so the parameter is assigned to itself.
  3. Using this unnecessarily everywhere, cluttering the code.
Chapter Summary
  • Classes define types and objects are instances of them, created with constructors.
  • Properties and access modifiers control how data is exposed.
  • Static members belong to the class, and this refers to the current object.
🔒

Chapter Quiz — Complete all 7 topics to unlock

0/7 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.