Dynamically cast native datatypes without switch statement?

M

Mario

I return (as a DataTable) the table schema information on various
columns in the database. For any column that has one I am accessing
the DEFAULT value specified in the database for that column. The
default value is returned as a string (e.g. "0" on a boolean or
"getdate()" on a datetime). In addition, because I have a working
dataset including schema, I can easily look up the DBType of the column
whose default I am working with. I would like to dynamically cast the
default value without using a switch statement.

foreach(DataRow row in rows)
{
string tablename = row["TABLE_NAME"].ToString();
string columnname = row["COLUMN_NAME"].ToString();
object defaultvalue = row["COLUMN_DEFAULT"];
DataColumn dc = ds.Tables[tablename].Columns[columnname];
// the following line does not work, but illustrates my intent
dc.DefaultValue = Convert.ChangeType(defaultvalue, dc.DataType);

}

In the past I have accomplished this with a switch statement similar
to:

object CastValue(DataColumn dc, string value)
{
object castvalue = null;

switch(dc.DataType.ToString())
{
case "System.Boolean":
castvalue = bool.Parse(value);
break;
case ...
case ... // and so on...
}

}

Obviously, the switch statement poses more work than seems necessary.
Any shortcuts for accomplishing the same? Even if the specifics of
this example are not practical, it seems useful to be able to
"dynamically cast" object values to native datatypes.

I would truly appreciate any feedback. Thanks.

Mario T. Lanza
Clarity Information Architecture, Inc.

CROSS POSTED FROM:
microsoft.public.dotnet.csharp.general
 
C

Cor Ligthert [MVP]

Mario,


I think that you can do this using reflection.

http://msdn.microsoft.com/library/d...ry/en-us/cpref/html/frlrfsystemreflection.asp

However that is not my favorite sport.

If you don't get a complete answer here than if it was my problem, I would
ask this question as well in the newsgroup
microsoft.public.dotnet.languages.csharp

And than as advice, make a new message more based on getting the type from
an object and using that.

I hope that this helps so far.

Cor
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top