When you're working with someone else's API, extension methods are a powerful tool: hey presto, you have a seat at the table with the API designers. For example, I don't like this common SharePoint idiom for translating a list column display name to the internal name:
string internalName = lst.Fields[displayName].InternalName;It's messy, and it punctures the list abstraction: I was working with a list, but now I have to deal with the SPFieldCollection within the list. Here's what I'd like instead:
string internalName = lst.InternalName(displayName);And, with the right extension method, I have it:
static class SPListExtYou can drop a class of extension methods right into a source file, and everything will work. But you're better off separating the class out as a class library. This involves a bunch of plumbing work. Here's a checklist:
{
public static string InternalName(this SPList lst, string displayName)
{
return lst.Fields[displayName].InternalName;
}
}
- One-time setup: find "gacutil.exe" on your development machine, and add its directory to your PATH environment variable. If you're in Visual Studio, exit/restart;
- Sign the library. This makes it GAC-able. Properties » Signing. Check "Sign the assembly". For the strong name key file, use "classname.snk". Don't use a password. After the .snk file is created, drag it to the Properties folder;
- Add a post-build event:
gacutil -i $(TargetPath)
This copies the library into the GAC, so that SharePoint can find it. (Caveat: development only! Not the right way for production deployment.) It also copies the library to PublicAssemblies, so that Visual Studio can find it when you add a reference. (If you have multiple Microsoft Visual Studio directories, try the highest-numbered one first.)
copy $(TargetPath) "C:\Program Files\Microsoft Visual Studio 9.0\Common7\IDE\PublicAssemblies"