Type switch?

  • Thread starter Thread starter xenophon
  • Start date Start date
X

xenophon

I am trying to do a switch on a Type. It's actually a DataType used to
type a column in a DataTable.
I have run through several blogs and am not sure what I'm missing or
why it can't be done.

My switch statement looks like this:

int typeEnum = myObject.GetType().GetHashCode();
switch( typeEnum )
{
case ( typeof(System.Int64).GetHashCode() ) :
bool ThisIsABigInt = yes;
break;

That does not work. But this does:

string typeEnum = myObject.GetType().ToString();
switch( typeEnum )
{
case "System.Int64":
bool ThisIsABigInt = yes;
break;


The method that does this switch gets called around a zillion times,
and all of that ToString() seems like a problem.

What is the best way to simply switch on an instance Type to perform
an action? There are 30 Type tests and I don't think writing 30 if
statements is the right way to do things. Is it?

Thanks.
 
What is the best way to simply switch on an instance Type to perform
an action? There are 30 Type tests and I don't think writing 30 if
statements is the right way to do things. Is it?

IMO it's better than the two alternatives you provided in your post.


Mattias
 
xenophon,
What is the best way to simply switch on an instance Type to perform
an action? There are 30 Type tests and I don't think writing 30 if
statements is the right way to do things. Is it?
As Mattias suggests, 30 if statements would be the way I would go.

I would however consider a switch statement on System.TypeCode for the known
TypeCodes, then a series of ifs for the others (System.TimeSpan for example
is not on TypeCode. You can use Type.GetTypeCode to get a type's TypeCode.

Alternatively I would consider creating a "strategy" object where the Type
is used to Index into a dictionary (HashTable) of "strategy" objects. One
specific "strategy" object for each Type you expect.
 
Back
Top