class Person { public string Name; public Person(string name) { this.Name = name; } public void PrintName() { System.Console.WriteLine(this.Name); } } var p = new Person("Alice"); p.PrintName();
The this keyword inside an instance method refers to the current object. Here, this.Name accesses the Name field of the Person instance, which was set to "Alice".
class Sample { public static void Show() { System.Console.WriteLine(this.ToString()); } } Sample.Show();
The this keyword cannot be used inside static methods because there is no instance of the class to refer to. This causes a compilation error.
struct Point {
public int X, Y;
public Point(int x, int y) {
this.X = x;
this.Y = y;
}
public void Move(int dx, int dy) {
this.X += dx;
this.Y += dy;
System.Console.WriteLine($"{this.X},{this.Y}");
}
}
var p = new Point(1, 2);
p.Move(3, 4);In a struct, this refers to the current value. The Move method updates the fields and prints the new coordinates.
class Box { public int Size; public Box() : this(10) { System.Console.WriteLine(this.Size); } public Box(int size) { this.Size = size; System.Console.WriteLine(this.Size); } } var b = new Box();
The parameterized constructor sets Size to 10 and prints it. Then the parameterless constructor prints this.Size which is still 10.
this keyword mean in the parameter of an extension method?In extension methods, this before the first parameter indicates the method extends that type, and inside the method, it refers to the instance of that type.
