2

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

nalka
  • 1,894
  • 11
  • 26
michasaucer
  • 4,562
  • 9
  • 40
  • 91

2 Answers2

5

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();
Johnathan Barclay
  • 18,599
  • 1
  • 22
  • 35
4

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 Type
  • inputType 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

Jamiec
  • 133,658
  • 13
  • 134
  • 193