I would like to merge two cases with arguments in a switch statement in C#.
It is easy to merge cases in case of chars, string and integers:
switch (int)
{
case 1:
case 2:
{
<do something>
}
}
and a lot of info can be found about this (e.g. How to merge two case statements in one switch statement) but this doesn't work for more complicated cases with for instance ICommand
s.
The problem + what I've tried
My code looks as follows:
public override Task<IEnumerable<IEvent>> Handle(ICommand value, CancellationToken cancellationToken)
{
switch (value)
{
case UpdateFeeCommand cmd:
{
ApplyCreate(cmd.Fee, cmd.Owner);
break;
}
case CreateFeeCommand cmd:
{
<identical implementation>
}
(...)
}
}
and I have tried to merge them like
case UpdateFeeCommand cmd:
case CreateFeeCommand cmd:
{}
case UpdateFeeCommand:
case CreateFeeCommand cmd:
{}
case UpdateFeeCommand, CreateFeeCommand cmd:
{}
et cetera, but this syntax doesn't work. Moreover, I've tried replacing cmd
with value
, but then value.Fee
and value.Owner
are not found and need the implicit conversion to cmd
.
Is it possible to merge these cases?