2

While I was cleaning the code for my project, I stumbled upon a method within the class like following (simplified)

public static class HelperClass
{
   public static void DoStuff(this DifferentClassName obj)
}

After performing a quick search, aside from definition, the search result gave me the following:

varname.DoStuff();

Obviously, I thought that it didn't have anything to do with the method in the class, so I commented out the class method so see if it would cause any errors. To my surprise, the line from search result was redded-out.

The snippet of the search result line is as following:

var varname = new DifferentClassName()
{
    //stuff inside
}

varname.DoStuff(); //<==what about parameter??

I initially thought that it was because a new instance of class created, but shouldn't it still be a parameter inside the line in question? Can anyone please explain why these methods are tied to each other, while the parameter inside the method call was omitted?

IAbstract
  • 19,551
  • 15
  • 98
  • 146
Vadzim Savenok
  • 930
  • 3
  • 14
  • 37
  • 2
    its a special type of method called an extension method. You can research them, but you can determine it is one in that it is 1) a static method in a static class 2) uses the `this` keyword on its first parameter. – Jonesopolis Sep 16 '16 at 21:18
  • @TamasHegedus While it did answer my question, I was not aware about the actual method. Is it still going to be marked as duplicate? – Vadzim Savenok Sep 16 '16 at 21:44
  • It is as it is going to have the same potential answers, but don't worry about it. You already have an answer here too, and your question still can be upvoted. – Tamas Hegedus Sep 16 '16 at 21:59

1 Answers1

4

Methods with (this Foo foo) are extension methods. Extension methods have certain rules that apply (read link provided).

When these methods are in proper static classes - e.g. public or internal - any object that is the subject of the extension method essentially has that method tacked on to it's API. The subject object is then assumed as the first parameter.

You can call extension methods in 2 ways:

// assuming extension class as follows
public static class Extensions {
    // Foo is the subject Type and foo the subject object
    public static void DoBarWithFoo(this Foo foo){
        // do something with foo
    }
}

var foo = new Foo();

// call ...
foo.DoBarWithFoo();
// or ...
Extensions.DoBarWithFoo(foo);
IAbstract
  • 19,551
  • 15
  • 98
  • 146
  • Then, is it similar to Javascript, where, say, you have function with 5 parameters, and you are calling function with 3 parameters, it only assumes values of first 3 parameters? – Vadzim Savenok Sep 16 '16 at 21:26
  • 1
    No, it's quite different, check the "extension methods" link that IAbstract provided – Roberto Sep 16 '16 at 21:40