Craig Gibbons' Lifeblog lifeblog://tri.eat.net

20Jan/060

A generic C# function for casting from Object to any type

A very common scenario in software development is getting data from a database and then reading that data into strongly typed variables. Mostly I do this in an OR (Object Relational) layer, but really it could be done anywhere. Prior to .NET 2.0 and the introduction of generics, one had to cast the values from a DataRow or IDataReader column value, returned as an object, as follows:

string description = Convert.ToString(row["Description"]);

This works, but one needs to do a Convert operation for every data type. Furthermore, the object may be a DBNull, in which case you'll get an InvalidCastException. There are various strategies for getting around this. I offer my solution here.

public static T ToType<T>(object value) {
 if(Convert.IsDBNull(value)) {
  return default(T);
 }

 return (T)Convert.ChangeType(value, typeof(T));
}

Typically, this function would reside in a helper class of some kind and called in the following way:

string description = DbHelper.ToType<string>(reader["Description"]);

For any other data type, simply replace <string> with whatever cast you wish to perform.

Filed under: Tech Leave a comment
Comments (0) Trackbacks (0)

No comments yet.


Leave a comment

No trackbacks yet.