Having following example:
public class Test{
public Animal DoSomething(AnimalCreateDto animal){
Animal created;
if(animal is DogCreateDto dogCreateDto){
Dog dog = new(dogCreateDto);
created = Create(dog);
}else if(animal is CateCreateDto catCreateDto){
Cat cat = new(catCreateDto);
created = Create(cat);
}
return created;
}
private Dog Create(Dog dog){ ... }
private Cat Create(Cat cat){ ... }
}
Is there any way to use e.g. the switch-case?
CodePudding user response:
Check out pattern matching
From the blog post above:
object obj = new Developer { FirstName = "Thomas", YearOfBirth = 1980 };
string favoriteTask;
switch (obj)
{
case Developer dev when dev.YearOfBirth >= 1980 && dev.YearOfBirth <= 1989:
// 1. This case is taken for the defined Developer object
favoriteTask = $"{dev.FirstName} listens to heavy metal while coding";
break;
case Developer dev:
// 2. This case matches too, but it's defined after the first one that matches
favoriteTask = $"{dev.FirstName} writes code";
break;
case Person _:
// 3. This case matches too for a Developer, as Person is a base class
favoriteTask = "Eat and sleep";
break;
default:
favoriteTask = "Do what objects do";
break;
}
CodePudding user response:
Declare an abstract method in the base type and implement it in child types.
abstract class AnimalCreateDto
{
public abstract Animal Create();
}
class DogCreateDto : AnimalCreateDto
{
public override Animal Create() { /* Create Dog */ }
}
class CatCreateDto : AnimalCreateDto
{
public override Animal Create() { /* Create Cat */ }
}
public Animal DoSomething(AnimalCreateDto animal)
=> animal.Create();
CodePudding user response:
The latest pattern matching (C#9) style would be
public Animal DoSomething(AnimalCreateDto animal) =>
animal switch
{
DogCreateDto dto => Create(new Dog(dto)),
CateCreateDto dto => Create(new Cat(dto)),
_ => throw new NotImplementedException()
};