.NET, Archive, C#
     

.NET Extension Methods

Starting in .NET 3.5 is a feature called extension methods. Extension methods allow developers to extend classes with their own instance methods. This is a concept often called mix-ins in other languages.

Take for example the following piece of code.

In the above, trivial, example we see a helper class that has a static method to determine is a string is “short”. While the example is ridiculous, it is helpful in illustrating the root desire for extension methods. Often times our source code is littered with helper class very similar to the above one.

Also littered around your code is undoubtedly usages of such utility classes. So, for example, you would have usages such as:

Extension methods in .NET 3.5 provide a syntactic short cut for the above. To change our IsShort function to be an extension of System.String prefix the this keyword to the parameter list.

That is all that is needed to turn an ordinary helper method into an extension method in .NET 3.5. There are, however, a few rules to keep in mind with extension method.

  • Only static methods of static classes can be extension methods.
  • The this keyword can only be applied to the first parameter.
  • Extension methods are only visible when their containing namespace is imported via C#’s “using” statement.

With those simple rules you start converting your static helpers into extensions on the classes that they service, allow for easier customization of the core .NET libraries (or other 3rd party libraries).

Never miss an article! Subscribe to my newsletter and I'll keep you updated with the latest content.

 

About Jason

Jason is an experienced entrepreneur & software developer skilled in leadership, mobile development, data synchronization, and SaaS architecture. He earned his Bachelor of Science (B.S.) in Computer Science from Arkansas State University.
View all posts by Jason →

Leave a Reply

Your email address will not be published. Required fields are marked *