Seeing as C# can\'t switch
on a Type (which I gather wasn\'t added as a special case because is
relationships mean that more than one distinct
You're looking for Discriminated Unions
which are a language feature of F#, but you can achieve a similar effect by using a library I made, called OneOf
https://github.com/mcintyre321/OneOf
The major advantage over switch
(and if
and exceptions as control flow
) is that it is compile-time safe - there is no default handler or fall through
void Foo(OneOf o)
{
o.Switch(
a => a.Hop(),
b => b.Skip()
);
}
If you add a third item to o, you'll get a compiler error as you have to add a handler Func inside the switch call.
You can also do a .Match
which returns a value, rather than executes a statement:
double Area(OneOf o)
{
return o.Match(
square => square.Length * square.Length,
circle => Math.PI * circle.Radius * circle.Radius
);
}