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.
GetType is unneccesary:
var result = input switch
{
A2 _ => RunMethod1(input),
A3 _ => RunMethod2(input),
A1 _ => RunMethod3(input)
};
However, a more OO approach would be to define a method on the types themselves:
public class A1
{
public string Id1 { get; set; }
public virtual void Run() { }
}
public class A2 : A1
{
public string Id2 { get; set; }
public override void Run() { }
}
Then it's simply:
input.Run();
You can, but in an inheritance hierarchy like that you need to start with the most specific and move down towards the least:
A1 inputType = new A2();
var result = inputType switch
{
A3 a3 => RunMethod(a3),
A2 a2 => RunMethod(a2),
A1 a1 => RunMethod(a1)
};
Note that
inputType is an instance, not an instance of TypeinputType is typed as the base class but can be an instance of any A1-3. Otherwise you'll get a compiler error.Live example: https://dotnetfiddle.net/ip2BNZ
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With