CSC510213. Do not use unsafe type conversion on SPListItem.

Description

SPListItem is untyped entity, so null reference exceptions on nullable types or wrong type conversion exception might arise.

Bad code:
string date = list.Items[0]["Date"].ToString();
DateTime date = (DateTime)list.Items[0]["Date"];
int x= ((SPFieldUserValue)list.Items[0]["User"]).LookupId;

Resolution

Consider Convert.ToXXX method or manual conversion to handle wrong/nullable types.

Correct code:
DateTime date = Convert.ToDateTime(list.Items[0]["Date"]);
DateTime? date = list.Items[0]["Date"] as DateTime?;

Links

Convert Methods

Last edited May 5, 2014 at 9:53 AM by dvd73, version 6

Comments

No comments yet.