Saturday, August 29, 2009

Two small SPListItem extension methods

So, it is about two small extension methods which do basically the same job – getting a specific field value from a SPListItem instance. Since LINQ to SharePoint is still not quite popular (let’s see if SharePoint 2010 will change that) the SPListItem indexer is the usual way to get the data from a SharePoint list item. It does the job but its main disadvantage is that it operates with objects which means no type safety, cumbersome code, type casts, additional checks, etc.

These two extension methods are generics methods as well – so in the generics parameter you basically specify the return type of the method. And why two – it’s simple – because of the big dichotomy in .NET types – reference and value types. The first method works with reference field value types, the second one with value types (check out the where clause in the methods’ declarations). And the latter’s return type is not actually the generics parameter type but its Nullable counterpart – the SPListItem’s indexer is always expected to return null-s, isn’t it?

    1     public static class ListItemHelper

    2     {

    3         public static T GetValue<T>(this SPListItem item, string fieldName) where T : class

    4         {

    5             object o = item[fieldName];

    6             if (o == null || !(o is T)) return null;

    7             return (T)o;

    8         }

    9 

   10         public static Nullable<T> GetValue2<T>(this SPListItem item, string fieldName) where T : struct

   11         {

   12             object o = item[fieldName];

   13             if (o == null || !(o is T)) return null;

   14             return (Nullable<T>)(T)o;

   15         }

   16     }

And here’s a small sample of how to use the methods:

    1     SPListItem it = list.Items[0];

    2     string title = it.GetValue<string>("Title");

    3     DateTime? created = it.GetValue2<DateTime>("Created");

Overloads of the methods which expect the GUID SPField ID-s can also be created.

1 comment:

  1. I tried for list item fields and properties for each version please help me any one tried that in client object model

    ReplyDelete