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.”



Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.