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;
}