Friday, May 6, 2011

Use of "this" keyword in formal parameters for static methods in C#

I've come across several instances of C# code like the following:

public static int Foo(this MyClass arg)

I haven't been able to find an explanation of what the this keyword means in this case. Any insights?

From stackoverflow
  • This is an extention method. See here for an explanation.

    it means that you can call

    MyClass myClass = new MyClass();
    int i = myClass.Foo();
    

    rather than

    MyClass myClass = new MyClass();
    int i = Foo(myClass);
    

    This allows the construction of fluent interfaces as stated below.

  • I just learnt this myself the other day: the this keyword defines that method has being an extension of the class that proceeds it. So for your example, MyClass will have a new extension method called Foo (which doesn't accept any parameter and returns an int; it can be used as with any other public method).

  • They are extension methods. Welcome to a whole new fluent world. :)

0 comments:

Post a Comment