0

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;
    }
lmcarreiro
  • 5,312
  • 7
  • 36
  • 63

1 Answers1

2

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
Selman Genç
  • 100,147
  • 13
  • 119
  • 184
  • I see now in Visual Studio, that when I point the mouse in the GetX token in these lines where there are errors, it shows "method group". I didn't realize that I can have a lot of overloads with different parameters and all of them are identified by the same name... – lmcarreiro Sep 03 '18 at 20:09