[2.0] Get a type and coerce value to that type
I have the ff. 'ugly' code:
Code:
private void InsertWhereParameter(WhereParameter whereParameter)
{
Type t = whereParameter.FieldValue.GetType();
switch (t.ToString())
{
case "System.String":
_dataAccess.AddWhereParameter(whereParameter.FieldName, (String)whereParameter.FieldValue);
break;
case "System.DateTime":
_dataAccess.AddWhereParameter(whereParameter.FieldName, (DateTime)whereParameter.FieldValue);
break;
Is there something I am missing that would make it work like...
Code:
Type t = whereParameter.FieldValue.GetType();
_dataAccess.AddWhereParameter(whereParameter.FieldName, (t)whereParameter.FieldValue);
TIA
Re: [2.0] Get a type and coerce value to that type
What you're missing is that there's a difference between a data type and a Type object. A Type object is an instance of the Type class that represents a data type. It's not a data type itself. In order to cast a refernce as a particular type you MUST know the type you're casting too at compile time. The point of casting is to tell the compiler that an object is a specific type. If you don't know the type until run time then it's a bit late to be telling the compiler anything.
Re: [2.0] Get a type and coerce value to that type
So there is really no other way to achieve it other than what I already have?
Re: [2.0] Get a type and coerce value to that type
There are other ways to do it but they'd all involve some sort of test, unless you actually pass the type in too. You could do that with a DbType value.