What is 'this' keyword used for in C#?

Experience Level: Junior
Tags: C#

Answer

'this' keyword works like a reference to an object that holds the method that is currently being executed. In the example below the 'this' keyword is used to refer to the property VolumeLevel. The keyword 'this' is not needed most of the time, so whenever you see it, you should be thinking whether the keyword is really needed and whether it couldn't be removed.

Example
public class Radio 
{
  public int VolumeLevel { get; set; }

  public void ShowVolume() 
  {
    var currentVolumeLevel = this.VolumeLevel;
	Console.WriteLine(currentVolumeLevel);
  }  
}
Related C# job interview questions
C# for beginners
C# for beginners

Are you learning C#? Try our test we designed to help you progress faster.

Test yourself