When something is done with the result of the switch expression before it is assigned/returned (e.g. call a member function), and the type is ambiguous (e.g. case bodies have multiple child types of a parent type), we have to apply a cast to at least one of the case bodies to tell the compiler which type it is, or it's a compile error.
Input code
public abstract class Animal
{
public abstract string Name { get; }
public Animal ToValidated()
{
if (Name is null)
{
throw new ArgumentNullException(nameof(Name));
}
return this;
}
}
public class Dog : Animal
{
public override string Name => "Dog";
}
public class Fish : Animal
{
public override string Name => "Fish";
}
public class TestAnimals
{
public Animal GetAnimal(int animalType)
{
return (animalType switch
{
0 => (Animal)new Dog(),
1 => new Fish(),
_ => throw new ArgumentException("Invalid animal type")
}).ToValidated();
}
}
Erroneous output
[...]
public class TestAnimals
{
public Animal GetAnimal(int animalType)
{
return (animalType switch
{
0 => new Dog(), // no cast, compile error
1 => new Fish(),
_ => throw new ArgumentException("Invalid animal type")
}).ToValidated();
}
}
For reference, the specific compiler error when attempting to compile the output:
No best type was found for the switch expression.[CS8506](https://msdn.microsoft.com/query/roslyn.query?appId=roslyn&k=k(CS8506))
Details
- Product in use: IlspyCmd
- Version in use: current master
When something is done with the result of the switch expression before it is assigned/returned (e.g. call a member function), and the type is ambiguous (e.g. case bodies have multiple child types of a parent type), we have to apply a cast to at least one of the case bodies to tell the compiler which type it is, or it's a compile error.
Input code
Erroneous output
For reference, the specific compiler error when attempting to compile the output:
Details