C# 3.0 and .Net Framework 3.5 in introduce several new features. One of them is extension methods. Extension methods enable you to “add” new methods to the existing types. Extension methods are a special kind of static methods, but they are called as same as the instance methods. In this blog I will show you how to extend SharePoint API by using extension methods.
Here are my extension methods for “SPList” object.
Application with the extension methods
You also can call the extension methods as static methods.
Output with the extension methods
Extension methods in C# 2.0
As I stated in the introduction to this article, the extension methods is a new feature of C# 3.0, and the SharePoint 2007 API is based on .NET Framework 2.0. If you try to use extension methods in a project targeting .NET Framework 2.0, you will get a compiler error when compiling your code, the error text is “Cannot define a new extension method because the compiler required type ‘System.Runtime.CompilerServices.ExtensionAttribute’ cannot be found”. Seems the compiler just needs to resolve ‘System.Runtime.CompilerServices.ExtensionAttribute’ to compile extension methods. So you can introduce your own ‘System.Runtime.CompilerServices.ExtensionAttribute’ class, then it worked correctly!
The brilliant workaround explained by Daniel Moth.
The syntax with extension methods is much more streamline and a lot easier to understand. It easier for developers to approach the object model without having to divide their attention between the SharePoint API and custom class libraries.