Convert "Int32" to type Int32

  • Thread starter Thread starter Joe
  • Start date Start date
J

Joe

I have data types stored in a field in a database and would like to use
something similar to GetType when reading these values.

string datatype = dr["DataTypeColumn"]

// something like this would be nice.
ConvertStringToCorrectDataType(datatype);

I guess I could just list all the string values of the data types and do a
comparision but I thought there would be some kind of built in method for
this.

Thanks,
Joe
 
I think that there is something missing from your question.
Specifically, you must have another column that holds the actual data,
no? Having nothing more than a string that says "Int32" doesn't get you
very far without a value to use with it.

Yes, there are ways using Reflection to instantiate an instance of a
type given its name. See the Type.GetType() static method, for
starters. Once you have a Type object then you can get the constructor
using Type.GetConstructor, and invoke the resulting constructor using
ConstructorInfo.Invoke, which will get you an object of the indicated
type.

However, I wonder if this is the best design: storing .NET Framework
type names in a database? What if some other language has to use the
database and read these type names? What if Microsoft changes the name
of a type? (Naah... they wouldn't do that, would they? :)

I would think that you'd be much better off storing a "type indicator"
in the database. Make up your own names or codes. Then write a method,
as you stated, that has a big "switch" statement that builds the
correct kind of object based on the name. This has two major
advantages:

1. Easier to understand, and thus easier to maintain. Newbie
programmers can read this code more easily than they can decipher
tricky calls to Reflection.
2. Language-independent. Non-.NET languages can easily read the
database and implement the same logic.

Just my two cents' worth....
 
Back
Top