Greg Beech Greg Beech - 1 year ago 120
C# Question

Closest C# equivalent to the F# match expression?

I'm in the situation where a lot of my classes are containers of well-known but unordered objects of different types, e.g. a container may look as follows:

public class Container
public A A { get; private set; }
public B B { get; private set; }
public C C { get; private set; }

public bool StoreIfKnown(object o)
// TODO...

So if
is of type
it should be stored in the
property, type
in the
property and so on.

In F# the
method could be written something like the following (excuse the syntax errors, my F# is not great and quite rusty):

match o with
| ?: A a -> A <- a; true
| ?: B b -> B <- b; true
| ?: C c -> C <- c; true
| _ -> false

But in C# the only way seems to be the rather verbose:

if (o is A)
this.A = (A)o;
return true;

if (o is B)
this.B = (B)o;
return true;

// etc.

return false;

I could do it with the
keyword to avoid the test/cast pattern which would be faster, but is even more verbose.

Is there any elegant way to do this in C#?

Answer Source

You could author an extension method on 'o' and helper classes to enable a programming model like

o.Match<A>( a => { this.A = a; return true; } )
 .Match<B>( b => { this.B = b; return true; } )
 .Else( () => { return false; } )

But be wary of doing too much DSL-like hackery here, lest you end up with an API only you understand.

See also

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download