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#?