Extension Methods

I’ve just started looking at C#, and having gone through some example code, noticed something unusual in a method definition. There was a method which included the keyword ‘this’ in the parameters. Here’s what it looked like:

 static bool Contains(this string keyString, char c)
     return keyString.IndexOf(c) >= 0;

After doing some looking around, I found out this is what is called an extension method.┬áThe difference between an extension method and a normal static one is that it allows you to use the method in a way that makes it look like it’s part of the type (that it’s extending).

Formally, per the Microsoft Documentation;

“Extension methods are defined as static methods but are called by using instance method syntax. Their first parameter specifies which type the method operates on, and the parameter is preceded by the this┬ámodifier. Extension methods are only in scope when you explicitly import the namespace into your source code with a using directive.”