I'd like to apply switch statement pattern matching to determine if I'm dealing with a specific generic type. The inner type may be one of several that inherit from an abstract class. Here's an example:
using System;
namespace ConsoleApp1
{
abstract class Vehicle
{
public abstract string Name { get; }
}
internal class Sedan : Vehicle
{
public override string Name => "Sedan";
}
abstract class AbstractLoad
{
public abstract string Name { get; }
}
internal class Oil : AbstractLoad
{
public override string Name => "Oil";
}
internal class Lumber : AbstractLoad
{
public override string Name => "Lumber";
}
class Semi<TLoad> : Vehicle where TLoad : AbstractLoad
{
public override string Name => "Semi";
public TLoad Load { get; set; }
}
class Program
{
static void Main(string[] args)
{
var vehicle = new Semi<Oil> {Load = new Oil()};
DescribeVehicle(vehicle);
}
static void DescribeVehicle(Vehicle vehicle)
{
switch (vehicle)
{
case Sedan sedan:
Console.WriteLine("This vehicle is a sedan");
break;
case Semi<AbstractLoad> semi:
Console.WriteLine($"This vehicle is a semi carrying {semi.Load.Name}");
break;
default:
Console.WriteLine("We don't know what kind of vehicle this is.");
break;
}
}
}
}
I'd like it to print, "This vehicle is a semi carrying Oil". However, it prints, "We don't know what kind of vehicle this is." Is there some way I can get it to match the Semi case?