What is the purpose of ‘this’ keyword in C#

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

Leave a Comment