I have this function:
static void Func1<T>(T x, T y)
{
dynamic result = ((dynamic)x + y); //line 1
dynamic result2 = (x + y); //line 2
}
This func can be executed as Func(1,2); However, line 1 is OK, while line 2 goes BANG (at compile time).
The exception thrown from line 2 is:
Operator ‘+’ cannot be applied to operands of type ‘T’ and ‘T’
So, we need to create an operator overload. Okay, so far so good.
But what about line 1? Shouldn’t it need a dynamic cast also on y?
((dynamic)x + (dynamic)y);
I understand that it is being evaluated at runtime, but why does the C# compiler accept the + operator in line 1 (i.e. wrongly assume that T can be + to something else)?
In your first example, by making
xadynamicyou’ve in effect made theoperator+operation dynamic as well. This gets rid of the type specifierTforx, thereby getting rid of the complaint thatThas no validoperator+.At run time dynamic binding will occur and evaluate the two operands to ensure that
operator+can be used:In your second example, the compiler knows the types for
x + yand is simply storing the result into adynamicvariable. Further usages ofresult2will be dynamically bound. This makes sense as there are no dynamic operations to the right of the assignment operator: