Tuesday, October 03, 2006
Quick conversion from DbType to System.Type Without Switch
I was looking for a simple way to convert from a DbType to a System.Type. DbType is an enum and System.Type is a struct (or class, I forget).
Now, if you have a parameter object that has a value you can write p.Value.GetType()--assuming p is your parameter name and value is not null. But, what if Value is null? The answer is to get the string value of DbType from its ToString method and then request the system type like this:
Assume you have:
IDataParameter p = new SqlParameter("@Foo", null);
p.DbType = some type;
then:
string _s = p.DbType.ToString();
Type _t = Type.GetType("System." + _s);
For all but a few types this works fine, which includes AnsiString, Binary, Date, Time, VarNumeric, AnsiStringFixedLength, StringFixedLength, and Xml. For these types simply write a conditional check. Its not a perfect solution but until someone (eh-hem! Microsoft!) builds DBTypeConverter this beats the heck out of a monolithic switch statement.
Now, if you have a parameter object that has a value you can write p.Value.GetType()--assuming p is your parameter name and value is not null. But, what if Value is null? The answer is to get the string value of DbType from its ToString method and then request the system type like this:
Assume you have:
IDataParameter p = new SqlParameter("@Foo", null);
p.DbType = some type;
then:
string _s = p.DbType.ToString();
Type _t = Type.GetType("System." + _s);
For all but a few types this works fine, which includes AnsiString, Binary, Date, Time, VarNumeric, AnsiStringFixedLength, StringFixedLength, and Xml. For these types simply write a conditional check. Its not a perfect solution but until someone (eh-hem! Microsoft!) builds DBTypeConverter this beats the heck out of a monolithic switch statement.
Subscribe to Posts [Atom]