Why the compiler can't handle these x3
and x4
assignments?
void X()
{
(Func<int, int>, int) x1 = (GetX, 1); // OK
object x2 = x1; // OK
object x3 = (GetX, 1); // Error CS8135 Tuple with 2 elements cannot be converted to type 'object'.
object x4 = (GetX, 1) as (Func<int, int>, int); // Error CS8307 The first operand of an 'as' operator may not be a tuple literal without a natural type.
object x5 = ((Func<int, int>, int))(GetX, 1); // OK
object x6 = ((Func<int, int>)GetX, 1); // OK
}
int GetX(int x)
{
return x;
}
Because a tuple does not have concrete type unless you cast it to more specific type. Your GetX
method might be convertible to various delegate types. So you will need to cast it to a specific one, compiler can't choose it for you.
The reason is similar to this case:
Delegate del = x => x * 2; // err
Delegate del2 = (Func<int,int>)(x => x * 2); // OK