Consider the following code in AutoMapper
CreateMap<ViewModel, ServiceModel>()
.ForMember(
x => x.Type,
opt => opt.MapFrom(y =>
y.TypeName switch
{
"FirstName" => typeof(FirstModel),
"SecondName" => typeof(SecondModel),
_ => null
}));
I have few different cases and I want to return a specific type for each string.
The compiler disagrees:
An expression tree may not contain a switch expression.
Why is that? I would expect that this feature, neatly called expression internally performs Expression.Switch, thus should be usable in expression trees.
I know that I can substitute with ternary operator syntax. I'd like to understand why it does not work.
Edit
Thanks Sweeper for pointing that that's not actually a switch expression. Guess I got carried on the convention train and got fooled by the naming.
Ivan Stoev I'm aware it's not supported but I am curious as to why. I understand why block scope is not supported, but switch case is very simple and declarative in nature, which would fit well in an expression tree.
Edit 2 Thanks to Jeroen Mostert comment bellow, I now understand that a switch case is far from simple internally and thus it has no place in expression trees.
Expression.Switch
represents aswitch
statement, not aswitch
expression. – Marcusmarcy?.
operator: "An expression tree lambda may not contain a null propagating operator.", value tuples: "An expression tree may not contain a tuple literal." etc.) – Obligationx switch { FirstModel m=>..., SecondModel m=>.....}
. – Axleswitch
expression is anything but simple from the compiler's point of view. It may be compiled down to a sequence ofif
/then
s, or a full-blownswitch
statement, it may involve tuple deconstruction, temporaries, constructor calls... It is not, in any case, considered a primitive expression of the expression tree API, which has traditionally allowed no newcomers in any case so as not to break providers (hence also no null propagation, no tuples, etc., even though those are conceptually much simpler thanswitch
). – Awaken