Streamline Your SharePoint Code Using Extension Methods

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:

        public bool SPListContainsField ( SPList list,
                                            string displayName,
                                            out SPField result )
        {
            result = default( SPField );
            try
            {
                result = list.Fields[displayName];
                return true;
            }
            catch
            {
                Trace.Write( string.Format( "Field '{0}' not found in list '{1}'",
                    displayName, list.Title ) );
            }
            return false;
        }

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:

image

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.

image

 

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.

13 comments

  1. I love extension methods, and for SharePoint development especially. I would suggest you to change your catch to a catch(ArgumentException) so you don’t catch generic exceptions.
    /WW

  2. Thanks, Wictor. I didn’t see the need for a specific exception type since there was only one line of code in the try block. Also, I’m not sure that ArgumentException would catch the index out of range condition. Nevertheless, you are quite right that generic catch statements are not best practice.

  3. Great idea! Myself being fairly saturated in the SharePoint world – it is hard to come by .NET goodies like this. Good find. I’ll have to check out your related posts. Any other .NET tricks like this on deck that I can look forward to reading?

    Phil

  4. "Turns out that as of version 3.0 of the .NET Framework, it is possible…"

    Not true…it is .NET 3.5 and C# 3.0…not .NET 3.0 (which is .NET 2.0 + WPF/WCF/WF/CardSpace).

  5. Nice find!

    IMHO extension methods are more convenience than readability though, so I would definitely use it sparsely as it can quickly make your code hard to read.

  6. I’m not talking about calling the method. I agree that its easier to read myObject.MyExtension() than SomeClass.MyExtension().

    I was in part refering to the Extension Method syntax itself (this in front of parameters) and the whole spookyness around static methods suddenly show up in intellisense.

    Also i got a bit annoyed on Extension Methods when i found that CLR 3.0 had added extension methods to ienumerator/ienumerable ( or was it icollection, i forgot) so that you now had a *ton* of methods before you got to Count. :-O

  7. I see. This is interesting, because I heard a similar complaint from a couple of other people. Personally, I don’t mind the syntax, except I would like it better if there were a way to extend static class methods as well. The ‘this’ syntax pretty much excludes having class level extension methods. Since they were modifying the language syntax, then they could have added a whole new syntax for extending existing classes.

  8. Hey John,

    Nice post on extensions. I have been using object extensions to add my own canned helper methods, but I have not been able to figure out how to add a custom property to an SPList object. Is there a possibility you could post a small snippet on how to accomplish this? After some exhaustive searching, I have been unable to find any examples.

  9. AFAIK, it is not possible to extend properties, only methods. I don’t know if extension properties are planned for the future, but there is a raging debate about whether they should be. The main objection appears to be over the proper syntax and scope.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.