Remember DateTime Casting With SP.ListItem Modified Property

I had this come up with a client this morning. To get down with it, consider the following client object model code:

ClientContext clientContext = new ClientContext(“http://test”);
List list = clientContext.Web.Lists.GetByTitle(“TestList”);
ListItemCollection listItems = list.GetItems(CamlQuery.CreateAllItemsQuery());
ListItem item = listItems[0];

// pay attention to this!
DateTime modifiedDate = (DateTime)item[“Modified”];

// Should use include to only use the properties that are required


In the above we have a couple things going on. Firstly, a ClientContext object is instantiated to represent the context for SharePoint objects and operations. Next, we are getting a SP.List object by using the ListCollection.GetByTitle method passing in the list name. Next, we are getting all the items from the list by using the SP.List.GetItems method then passing in the CamlQuery.CreateAllItemsQuery method. Indexing the collection, we are getting a test SP.ListItem. Now this is where the context of this post comes into play. If you are getting the Modified property of the list item, you have to remember to explicit cast to a DateTime type (you could safely cast as well). If you don’t, the value **may** display empty (it’s not consistent across list types)!