The SharePoint API can be vexing for developers who are not used to the little 'gotchas' that pop up here and there. This can lead to lots of wasted time when all you want to do is determine if a list contains a certain field, or perform a standard operation on a list. For example, say you have a task list and you want to get the list of overdue tasks or the list of tasks that will become due in the next week. Of course, you could write the code in a separate utility library and pull it out when you need it. But wouldn't it be great if you could simply extend the SPList object so that it included your custom properties and methods?
What I'm after here is a way to essentially derive a new class from SPList that includes my additional properties and methods without having to embed the original SPList object inside of it. That way, I can pass the same object to code that expects a standard SPList object and avoid having to build additional infrastructure around my extended class to make it look and behave like a standard SPList.
Let's start with a simple example - determining if a list contains a given field. Normally, we'd have to write this in a for loop or inside a try/catch block to avoid the exception that is thrown when testing for a non-existent field. The code might look something like this:
Turns out that as of version 3.0 of the C# language (.NET Framework 3.5), it is possible to write your own custom code and attach it to any .NET class as an extension method. The method appears as part of the IntelliSense for the extended class, and the compiler generates the appropriate IL code to call your extension method as though it were part of the class. This means you don't have to own the code for the class in order to extend it or otherwise modify it in any way.
To add this method, you would start by declaring a namespace to hold your extension and then declaring a static method that takes an SPList as the first parameter, prefixed with the "this" keyword. So the same method from above could be packaged as follows:
All you have to do to use the extension is include the namespace in your code. The nice part is all that IntelliSense goodness and the handy illusion that your method is now encapsulated within the definition of SPList.
Extension methods can make it easier for novice SharePoint developers to approach the object model without having to divide their attention between the core API and custom class libraries, which tend to have a broader focus than simply extending a given component.