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:
Syntax
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
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());
}
}
Login to try C/C++/Java/PHP code in the editor
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
- Using
thisinside a static method, where it is not available. - Naming a parameter the same as a field and forgetting
this.when assigning, so the parameter is assigned to itself. - Using
thisunnecessarily 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
thisrefers to the current object.
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: