There's nothing wrong with using tuples or pattern matching. If anything, these allow you to write cleaner code and avoid spreading your logic to multiple methods.
C# 7 doesn't allow you to match against tuple values yet. You can't compare two tuples with the ==
operator either. What you can do, is use Equals
two compare two value tuples:
if (_test.Equals(('A','B'))
{
Console.WriteLine("Case A ok.");
}
else if (_test.Equals(('D','\0'))
{
Console.WriteLine("Case D ok.");
}
It would seem that you are trying to create a state matchine for a parser(?), that matches specific patterns. This can work with pattern matching if you specify different state classes instead of using a single tuple for all cases.
All you need to do is specify a single IState interface without methods, and use it in all state classes, eg:
interface IMyState {};
public class StateA:IMyState{ public string PropA{get;set;} };
public class StateD:IMyState{ public string PropD{get;set;} };
...
IMyState _test= new StateD(...);
switch (_test)
{
case StateA a:
Console.WriteLine($"Case A ok. {a.PropA}");
break;
case StateD d:
Console.WriteLine($"Case D ok. {d.PropD}");
break;
default :
throw new InvalidOperationException("Where's my state ?");
}
The a
, d
variables are strongly typed, which means you don't have to add anything to the IState
interface. It's there only to satisfy the compiler.
By using structs instead of classes for the state types, you'll get the same memory benefits you would with tuples. If you want to use deconstruction, you can add a Deconstruct
method to each type, or use Deconstruct
extension methods in a separate static class.
when
syntax.case Rectangle r when r.Height == r.Width
is not very constant :) – Brnaby