switch over types

dear Folks,

I just corrected a mishap in my program that has to do with switch possibility. The bug was that an integer holding an internal representation of the actual Type ran out of sync with the actual Type. Hence the switch over the integer ran into a casting  failure.
The problem at hand is copying data into a object holding many different types. Frankly at some point I intend to dispose of that integer since it is merely historic clutter.
The current code at hand suggest the following solution

switch (obj.GetType())
{
    case Type1: tgt = new Type1(obj); break;
    ....
}

however the .Net 2.0 C# help still suggest that it is only possible to switch integers or strings, curently I'ld have to write out the above in a sequence of

if (obj is Type1)
    tgt = new Type1(obj);
else if .......

Though of course there are many ways to code things, and I can certainly work around this, I just wondered why <strong>switch</strong> is limited to <strong>integral and string expressions</strong>. I do think the above sample situation could be handled by a compiler, I personally like the switch  over the if ... sequence


Just as an additional note: the above would also suggest that it could benefit from some means of <strong>overriding a base class copy constructor</strong> though I have no clue on how to do this,  other then perhaps the above switch explicit or implicitely implemented in the base class copy constructor. Note in case this would be implicit, one needs to have means  to change the call on occurance of certain condition.


Answer this question

switch over types

  • switch over types