Try this instead:
// T - the type you are attempting to retrieve.
// o - the data that you want to turn into a T
T get<T>(object o)
{
// handle nulls - turns Nullables into null, reference
types to null and value types to 0.
if (o == null || o == DBNull.Value)
{
return default(T);
}
// we have real data so cast it
else
{
// Gets the underlying nullable type. Null if the type
is not Nullable.
Type t = Nullable.GetUnderlyingType(typeof(T));
// ChangeType is especially nice for dealing with
casts.
// Where explicit casting fails, ChangeType often
succeeds.
// It is dangerous to convert from Object to
Nullable<Udirectly, since Object may not be a U.
// However, from U to Nullable<Ualways succeeds, so
make Object into U first.
// Since we already handled nulls, we need not worry
about casting away null-ness.
return (T)Convert.ChangeType(o, t == null ?
typeof(T) : t);
}
}
This generic method allows you to send in whatever type you desire to
pull off as T. This method will do its best to take what is on the
database and turn it to your type.
It even handles Nullable types so you can put nulls into numbers and
dates.
It will return nulls into the default value of your type, so numbers
become 0, Dates become DateTime.MinValue and reference types become
null.
This is absolutely necessary to provide an efficient, universal and
safe way of managing data types for business objects, especially if
your DBAs like to change precisions on your a lot.
I have been using this code for months now and have been pleasantly
surprised how little I have to worry about guess work anymore.
Let me know if you find any problems with it. Like I said, we have
gone months without any issues at all.
Cheers,
Travis