Mega Code Archive

 
Categories / C# Book / 01 Language Basics
 

0128 this keyword

this is referencing the current type. using System; class Rectangle { public int Width; public int Height; public Rectangle(int w = 5, int h = 6){ this.Width = w; this.Height = h; } } class Program { static void Main(string[] args) { Rectangle r = new Rectangle(); Console.WriteLine(r.Width); Console.WriteLine(r.Height); } } The output: 5 6 this can be used to avoid name shading. using System; class Rectangle { public int Width; public int Height; public Rectangle(int Width, int Height){ this.Width = Width; this.Height = Height; } } class Program { static void Main(string[] args) { Rectangle r = new Rectangle(2,3); Console.WriteLine(r.Width); Console.WriteLine(r.Height); } } The output: 2 3 this cannot be used in static context.