C#C
C#3y ago
alistairv

❔ Pattern matching on multiple cases with the same-typed members

Hello, I am currently stuck with code like this:

public void Foo(Bar bar) {
  if (bar is Bar1 { Prop1: var p1 }) {
    // do stuff with p1
  } else if (bar is Bar2 { Prop2: var p2}) {
    // do the exact same stuff with p2
  } 
  // etc
}


where Bar1 : Bar, Bar2: Bar, ... and the type of Prop1, Prop2, ... is the same. Since Bar is not my type, I cannot simply modify it to suit me better.

My question: Is there a way to handle this more elegantly inside the method (aside from extracting a local function)? I am thinking of some syntax like

if (bar is Bar1 { Prop1: var p } or Bar2 { Prop2: p } or ...) { 
  // do stuff with p 
}


but unfortunately this is invalid syntax. Same holds for

TypeOfProp p = null;
if (bar is Bar1 { Prop1: p } or Bar2 { Prop2: p } or ...) { 
  // do stuff with p 
}
Was this page helpful?