.NET, Archive, C#

.NET Extension Methods

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

public static class StringHelpers{
	public static bool IsShort(string s){
		if(s == null || s.Length < 10)
			return true;
		return false;
	}
}

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:

     string name = "Jason";
     if(StringHelpers.IsShort(name)){
          //do something
     }

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.

	public static bool IsShort(this string s){
		if(s == null || s.Length < 10)
			return true;
		return false;
	}

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

About Jason

Jason is an experienced Entrepreneur & Software Developer with a demonstrated history of working in the oil & energy industry. Skilled in Management, Mobile Development, Data Synchronization, and SaaS Architecture. Strong engineering professional with a 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 *