469,133 Members | 1,281 Online
Bytes | Developer Community
New Post

Home Posts Topics Members FAQ

Post your question to a community of 469,133 developers. It's quick & easy.

Not a Question - Anyone tired of guessing types coming from a database?

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

Oct 19 '07 #1
0 1027

This discussion thread is closed

Replies have been disabled for this discussion.

Similar topics

9 posts views Thread by אלחנן | last post: by
5 posts views Thread by Don Vaillancourt | last post: by
8 posts views Thread by Ivan Shevanski | last post: by
6 posts views Thread by Mike | last post: by
21 posts views Thread by yeti349 | last post: by
1 post views Thread by pamelafluente | last post: by
1 post views Thread by Fregas | last post: by
reply views Thread by zhoujie | last post: by
By using this site, you agree to our Privacy Policy and Terms of Use.