Extension methods explained
Naturally to add new method to a class prior to .NET 3.0 you would have to extend that class, and to extend that class you would have to have access to the source code.
In .NET 3.0 and above that is no longer the case, you can use a new feature introduced in .NET 3.0 that enable you to "add" methods to existing types without creating a new derived type.
An example of creating an extension methoding
using System;using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.SharePoint;
namespace ExtensionMethods
{
public static class SharePointExtensions
{
//In an extension method, their first parameter specifies which type(SPWeb)
//the method operates on,
//and the parameter is preceded by the this modifier
//Thus we are extending the SPWeb type by adding the listExists method without actually
//creating a new class derived from SPWeb in this case
public static bool listExists(this SPWeb web, string listName)
{
return web.Lists.Cast<SPList>().Any(l => l.Title.Equals(listName));
}
//As well the following example shows an extension method defined for the
//System.String class
public static int WordCount(this String str)
{
return str.Split(new char[] { ' ', '.', '?' },
StringSplitOptions.RemoveEmptyEntries).Length;
}
}
}
Step By Step walkthrough
- Create an Extension project like in the above example
- Use the extension method in the application. In this case I'm creating a SharePoint list using a console application.
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.SharePoint;
namespace ExtensionMethods
{
public static class Program
{
static void Main(string[] args)
{
using (SPSite siteCollection = new SPSite(@"http://personal.portal.com:12345"))
{
using (SPWeb web = siteCollection.RootWeb)
{
SPListCollection lists = web.Lists;
//using the extension method
if (!web.listExists("listName"))
{
//if list does not exist then add it to the SPListCollection
lists.Add("listName", "list Description", SPListTemplateType.GenericList);
}
//Instantiate a SP List Object and assign the newly created list, or existing list if it already
//exists in the SPListCollection.
SPList testList = lists["listName"];
testList.Fields.Add("SPFieldOne", SPFieldType.Text, false);
testList.Fields.Add("SPFieldTwo", SPFieldType.Boolean, false);
}
}
}
}
}