Dynamic data casting

  • Thread starter Thread starter Trev
  • Start date Start date
T

Trev

Hi,
I have a series of functions which do the following:

ValidateData( args ); //args if of type ArrayList
// Work out if the data is valid or not, and work out the type of
args[1] - int, string, whatever?

if((bool)args[0]) // valid data
{
WriteDataToDB( args[1] );
}

However, it fails, as arg[1] is of type object, and I need to cast it
to type int, string whatever.
Rather than do a big switch statement, testing the type of args[1], is
there a way of
simply casting it using a function like:

ValidateData( args, ref type TypeOfArg1 ); //args if of type ArrayList
// Work out if the data is valid or not, and work out the type of
args[1] - int, string, whatever?
// work out type of args[1]

if((bool)args[0]) // valid data
{
WriteDataToDB( (TypeOfArg1)args[1] );
}

TIA

Trev
 
Hi Trev,

No, there isn't a way to cast a boxed System.Int32, for example, into a
System.Int32 variable or method argument at runtime unless it's hard-coded
using an explicit cast. Even conversion methods such as Convert.ChangeType
return System.Object, so even if you really mean conversion, not casting, it
still wouldn't work.

Why do you need it cast in the first place?

Have you overloaded the WriteDataToDB method to take typed arguments such as
bool and string?

Just add one more overload: object :)
 
Hi Dave,
The reason why I thought about run-time casting was because the
original data comes from a spreadsheet, and the values come as strings.
I then need to do a check as different cells in the sheet can only have
specified data types (eg row 1 can only be ints, row 2 only doubles
etc.). So, once I know the value and do a lookup on the datatype, I
then have to cast the string to ....whatever, as the database is very
fussy about such things.

Hope this explains it!
 
Hi,

What is the signature of your WriteDataToDB method?

If you're converting the data in your ValidateData method to the appropriate
Type, it still has to return System.Object. That doesn't mean the Type is not
what it was converted to, it's just being passed around as an object. I
assume that your WriteDataToDB method really only needs to accept
System.Object.

You may want to post the WriteDataToDB code if you are unsure what I mean and
I'll try to explain it better.
 
Back
Top