0

So we can do a fallthrough on switch statements and we can do switch statements on object type but is there a way to do a fallthrough on object types so that we can say "If it's any of these types of objects, call this method, pass in the object and I'll handle it there"?

Normally, each case statement must have a unique variable name so using the same variable name seems to be out of the picture here but if I can do null checking based on as casting, that will work so I know which one to send.

For example:

switch (myObject){
    ... //other cases
    case MyObjectType1 myObjectType1 :
    case MyObjectType2 myObjectType2 :
    case MyObjectType3 myObjectType3 :
    case MyObjectType4 myObjectType4 :
            var objectEvent = myObjectType1; //error here
            ///some other magic here
            HandleMyObjectTypes(myObjectType);
                    break;
}    

The problem I get is Use of unassigned local variable 'myObjectType1' so I can't even do as casting for null checking so that I can grab the one that it really is so that I can hand it off to my handling method for those specific types. The difficulty here is that I can't refactor the whole current method to support this pattern approach.

I'm sure there's some simple pattern or concept I'm missing but what is it?

Edit: What I'd like to do is this:

switch (myObject){
    ... //other cases
    case MyObjectType1 myObjectType1 :
    case MyObjectType2 myObjectType2 :
    case MyObjectType3 myObjectType3 :
    case MyObjectType4 myObjectType4 :
            var objectEvent = myObjectType1 ?? myObjectType2;
            objectEvent = objectEvent ?? myObjectType3;
            objectEvent = objectEvent ?? myObjectType4;

            HandleMyObjectTypes(objectEvent);
                    break;
}    
user4593252
  • 3,496
  • 6
  • 29
  • 55
  • Depending on which C# version you are using, there are several options: see https://stackoverflow.com/a/299001/7445285 – Max Xapi Oct 30 '20 at 13:24
  • I saw that when I was researching. I don't see how it applies? – user4593252 Oct 30 '20 at 13:28
  • What type do you expect the compiler to infer for `objectEvent` in your last sample? Bearing in mind that the types of variables is fixed at compile time. – Damien_The_Unbeliever Oct 30 '20 at 13:42
  • All I want is the object at the point of the code snippet here. I'll handle it in the HandleMyObjectTypes method. All I care is that I have the object and it's not null. The caveat is that some types are handled similarly while others have a LOT I have to do with them so the switch statement isn't the best place for that. – user4593252 Oct 30 '20 at 13:51

0 Answers0