Greg Beech Greg Beech - 2 months ago 17
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
o
is of type
A
it should be stored in the
A
property, type
B
in the
B
property and so on.

In F# the
StoreIfKnown
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
as
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

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

http://blogs.msdn.com/lucabol/archive/2008/07/15/a-c-library-to-write-functional-code-part-v-the-match-operator.aspx