Is it possible to create switch expression in C# 8 based on input type?
My input classes looks like this:
public class A1
{
public string Id1 {get;set}
}
public class A2 : A1
{
public string Id2 {get;set}
}
public class A3 : A1
{
public string Id3 {get;set;}
}
I want to run diffrent methods based on input type (A1, A2, or A3):
var inputType = input.GetType();
var result = inputType switch
{
inputType as A1 => RunMethod1(input); // wont compile,
inputType as A2 => RunMethod2(input); // just showing idea
inputType as A3 => RunMethod3(input);
}
But it wont work. Any ideas how to create switch or switch expression based on input type?C
You could use pattern matching, checking for the most specific types first.
GetTypeis unneccesary:However, a more OO approach would be to define a method on the types themselves:
Then it's simply: