3

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 ICommands.

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?

Casper Dijkstra
  • 1,615
  • 10
  • 37
  • 7
    If `UpdateFeeCommand` and `CreateFeeCommand` are unrelated types which just happen to both have properties with the same names, then you can't write code which treats them both as the same type. What you *can* do is define an interface (or base class) which defines those common properties, and have `UpdateFreeCommand` and `CreateFreeComment` both implement that interface. Then you can write `case IFreeCommand cmd` to handle both commands. – canton7 Nov 13 '20 at 10:20
  • In this instance you'd normally take the base class or some shared interface of `UpdateFeeCommand` and `CreateFeeCommand`, maybe `FeeCommand` or something like that and use it as the case. The "downside" to this is however that every `FeeCommand` (even those you don't want to handle this way) will be handled like this, except if you insert the specific case before the base case and break out of it. – MindSwipe Nov 13 '20 at 10:22
  • Also, this looks kinda weird, you're doing `ApplyCreate` with the `Fee` of an `UpdateFeeCommand`. Purely judging by naming you'd probably want to `ApplyUpdate` no? – MindSwipe Nov 13 '20 at 10:23
  • You didn't show `{ }` part, but that's the most important one. It's arguably harder to have *same* code for different types. You just need to refactor common part (if its big enough) into a method (local functions are nut) and call it from 2 different `case`s. – Sinatr Nov 13 '20 at 10:37
  • Do `Fee` and `Owner` both defined in `ICommand` interface? – Evk Nov 13 '20 at 10:46
  • @Evk `Owner` is defined in the `ICommand` interface but `Fee` is not. – Casper Dijkstra Nov 14 '20 at 10:02

0 Answers0