Vadzim Savenok Vadzim Savenok - 2 months ago 7
C# Question

Does C# allow omitting class parameter inside its methods?

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?

Answer

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);