© 2026 Hedgehog Software, LLC

TwitterGitHubDiscord
More
CommunitiesDocsAboutTermsPrivacy
Search
Star
Setup for Free
C#C
C#•3y ago•
11 replies
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
}
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, ...
Bar1 : Bar, Bar2: Bar, ...
and the type of
Prop1, Prop2, ...
Prop1, Prop2, ...
is the same. Since
Bar
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 
}
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 
}
TypeOfProp p = null;
if (bar is Bar1 { Prop1: p } or Bar2 { Prop2: p } or ...) { 
  // do stuff with p 
}
C# banner
C#Join
We are a programming server aimed at coders discussing everything related to C# (CSharp) and .NET.
61,871Members
Resources

Similar Threads

Was this page helpful?
Recent Announcements

Similar Threads

✅ Switch pattern matching with integers
C#CC# / help
3y ago
Pattern Matching to Check if 4 uint have the same value
C#CC# / help
4y ago
✅ Using Params with Pattern Matching Switch statement
C#CC# / help
2y ago
❔ How to replace string.IsNullOrWhiteSpace() with pattern matching?
C#CC# / help
3y ago