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

c#

Solution

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

Problem

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?

Original source

Related problems