What is the purpose of 'this' keyword in C#

Viewed 4954

Since variables declared inside a method are available only within that method, and variables declared private within a class are only available within a class. What is the purpose of the this key word? Why would I want to have the following:

private static class SomeClass : ISomeClass
{
    private string variablename;
    private void SomeMethod(string toConcat)
    {
        this.variablename = toConcat+toConcat;
        return this.variablename;
    }
}

When this will do the exact same thing:

private static class SomeClass : ISomeClass
{
    private string variablename;
    private void SomeMethod(string toConcat)
    {
        variablename = toConcat+toConcat;
        return variablename;
    }
}

to practice my typing skills?

19 Answers

There are a couple of cases where it matters:

  • If you have a function parameter and a member variable with the same names, you need to be able to distinguish them:

    class Foo {
      public Foo(int i) { this.i = i; }
    
      private int i;
    }
    
  • If you actually need to reference the current object, rather than one of its members. Perhaps you need to pass it to another function:

    class Foo {
      public static DoSomething(Bar b) {...}
    }
    
    class Bar {
      public Bar() { Foo.DoSomething(this); }
    }
    

    Of course the same applies if you want to return a reference to the current object

In your example it is purely a matter of taste, but here is a case where it is not:

private string SomeMethod(string variablename)
{
    this.variablename = variablename;
    return this.variablename;
}

Without this, the code would work differently, assigning the parameter to itself.

There are many cases where this is useful. Here's one example:

class Logger { 
   static public void OutputLog (object someObj) {
      ...
   }
}

class SomeClass { 
   private void SomeMethod () { 
      Logger.OutputLog (this);
   } 
}

Here's another example. Suppose I were writing a Stream.Out method that outputs an object, and returns a reference to the stream itself, like so:

class Stream {
   public Stream Out (object obj) { 
      ... code to output obj ...
      return this; 
   }
}

Then, one could use this Out call in a chained mode:

Stream S = new Stream (...);
S.Out (A). Out (B). Out (C);

In addition to the "field disambiguation" and "passing a reference of the current isntance" answers (already given), there is an additional scenario where this is necessary; to call extension methods on the current instance (I'm ignoring the usage of this in declaring an extension method, as that isn't quite the same meaning as the question):

class Foo
{
    public void Bar()
    {
        this.ExtnMethod(); // fine
        ExtnMethod(); // compile error
    }
}
static class FooExt
{
    public static void ExtnMethod(this Foo foo) {}
}

To be fair, this isn't a common scenario. A more likely one is simply to make code more readable, for example:

public bool Equals(Foo other) {
    return other != null && this.X == other.X && this.Y == other.Y;
}

In the above (or similarly for Compare, Clone etc), without the this. I find it a little... "unbalanced".

You need this if your method-parameter has the same name as the field.

private string variablename;
private void SomeMethod(string variablename)
{
    this.variablename = variablename+variablename;
    return this.variablename;
}

In most cases, using this simply clutters the code. However, I've seen it used by other programmers, presumably to trigger the intellisense for members of the local class.

The this keyword is also required for use in extension methods.

public static class MyExtensions
{
    public static int WordCount(this String str)
    {
        return str.Split(new char[] { ' ', '.', '?' }, StringSplitOptions.RemoveEmptyEntries).Length;
    }
}  

Firstly, your examples are flawed because you've marked the class as static, so it cannot be instantiated.

Regardless, this is simply a reference to the current instance. It can be used to resolve conflicts between local variables and member variables, for example:

public class Foo
{
    private string baz;

    public void Bar(string baz)
    {
        this.baz = baz;
    }
}

It can also be used simply as an object in its own right, for example:

public class Foo
{
    public List<Foo> GetList(string baz)
    {
        var list = new List<Foo>();
        list.Add(this);

        return list;
    }
}

(Not that this example is particularly useful, but you get the idea.)

Edit: A more realistic example is the event model in .NET:

public class Foo
{
    public EventHandler SomeEvent;

    public void Bar()
    {
        if (SomeEvent != null)
        {
            SomeEvent(this, EventArgs.Empty);
        }
    }
}
  1. this signifies your current class instance member not
    a. your base class member
    b. scope member
    c. static member
  2. To make your code more readable.

The first thing that comes into my mind is readability and/or personal preference.

Sometimes when I am working with a rather large class... or a class with a base class (where I cannot "see" some variables)... I utilize the "this" keyword... at minimum for intellisense in Visual Studio.

Outside of perhaps Javascript, "this" is mostly a placeholder keyword and it is most useful is making your intent obvious when writing a piece of code.

Basically it will help with readability.

First and foremost, this is necessary when a class method needs to pass a reference to the object to some method in another class.

For example:

class Image
{
    void Refresh()
    {
        Screen.DrawImage(this);
    }
}

Unlike some other scenarios where using or not using "this." is a matter of style, or a means for resolving an artificial ambiguity.

I respectfully disagree with some of the other posters. In C#, it isn't just a matter of taste; it is also in line with Microsoft's C# style guidelines (both internally and externally, though they do not seem to ahdere to their own guidelines internally).

There are examples of cases when the notation you used will not work:

private void DoSomething(object input) 
{ 
    input = input; 
} 

Instead, you would need to use the following notation:

private void DoSomething(object input) 
{ 
    this.input = input; 
} 

this refers to the instance of the class, and in the example you show us: you use this to refer to the field called variablename.

If you had a local variable or parameter with the same name, you would need to have a way of differentiating between them. In that case this will refer to the field, while not prefixing with this refers to the local variable or parameter.

You should have a naming convention that helps you differ between fields and locals. This will save you from the troubles that could occur if you later added a local with the same name to your method. (Since code without this would then break...)

It is a style issue primarily. If your method has a variable name that's the same as a private class member, using this helps disambiguate. This could potentially prevent silly bugs.

Common use is with constructor arguments that have the same name:

public SomeClass(string variablename)
{
   this.variablename = variablename;
}

1) First, and the most important, is a situation when an object needs to pass a reference to itself:

public class Element{
//...
public Element Parent;
public Element Root()
{
 if( Parent == null )
  return this;
 return Parent.Root();
}
}
public void OnEvent()
{
 Event(this, new EventArgs());
}

In fluent interface:

public class Query{ public Query Add(Parameter parameter) { _list.Add(parameter); return this; } }

2) Second, in and extension method:

public class Extension
{
 public Element Root(this Element element) {
  if( element.Parent == null )
   return element;
  return element.Parent.Root();
 }
}

3) Third, and you really don't need it, to distinguish parameters from class members. You don't need it, because a good coding convention saves you from using 'this' keyword.

public class Element
{
 public Element Parent;
 publlc void SetParent(Element parent)
 {
   // this.Parent = parent; // see, you don't need it
   Parent = parent;
 }
}
//...
public class Element
{
 public Element _parent;
 public Element Parent { get { return _parent; } }
 publlc void SetParent(Element parent)
 {
   // this._parent = parent; // see, you don't need it
   _parent = parent;
 }
}

There is one principle that should guide you in deciding whether or not to use 'this'. Do you need to refer specifically to THIS instance of the class? If you do, then use 'this'. Otherwise, leave it out.

The Logger example another poster provided is a good example of this. He could not rely on an implicit this, since he needed the object itself.

There is no point on using 'this' as a prefix to a method of the class itself, in the class itself, since it is implicit.

I can't help but...

if (this == null)
    throw new NullReferenceException();

[KIDDDIIIING!!!]

Related