A better way to obtain fields values of an SPListItem


Obtaining the value of a particular field (SPField) of a list item (SPListItem) is quite awkward. First of all you have to pass either the index, Id or the InternalName of an existing field. If the field exists a value of the object type is being returned. In some cases that value can be null. If it’s not you can cast it to its origin type as in most cases defined by the SPField.FieldValueType Property. Imagine doing all that each time you want to retrieve a field value. Isn’t there a better way?

Introducing the TryGetValue extension method

To simplify the task as described above I have created an extension method using generics:

C sharp code of the try get value method

What is it doing?

The method does exactly the same what I describe above: it retrieves the value of the given field for the current list item. Because it might just happen that you’re passing an invalid id, the whole process of retrieving and processing the value is wrapped in a try catch clause.

The method encapsulates the whole process of retrieving and process the value what leads to simplification of your code. Compare the standard approach of retrieving a field value with how you would do the same using the extension method:

Comparing two different approaches of retrieving the field value from a list item. Using the extension method is more efficient than using the standard approach

See the difference? Using the extension method all you need is one line of code. The value you get is type safe and you know is different than null.

Under the hood

I have chosen to make it an extension method to make using it more intuitive. Getting the value of the particular field of the particular list item is what you want to do: why not calling the method like that?

Furthermore I have decided to use generics to provide the type safety of the retrieved value. Like that you have just one method which works for every single type out there including your custom field types:

Using the same extension method with different value types

To provide you some feedback about the value I have decided to use the try pattern. The method tries to retrieve the value of the particular field. It returns true if succeeded and false if failed. To prevent you from making an extra call to get the value I have decided to use an out parameter so you can directly use the value in your custom code.

As you’ve probably noticed in the example above I’m referring to fields using classes instead of typing the internal names. Using the latest version of Imtech Fields Explorer you can automatically generate wrapper classes for content types so you will never have to use any internal name again.

The TryGetValue extension method: do you love it or hate it?

Technorati Tags: SharePoint, SharePoint 2007, WSS 3.0, MOSS 2007

Others found also helpful: