Roslyn: Why assign Func using ternary operator give me Error ?

Created on 25 Jan 2017  路  1Comment  路  Source: dotnet/roslyn

Why the statements 1 and 2 compile, but 3 give me the following error ?

Error CS0173 Type of conditional expression cannot be determined because there is no implicit conversion between 'lambda expression' and 'lambda expression

  1. var func = step >= 0 ? (Func<int, int, bool>)((a, b) => a >= b) : (a, b) => a <= b;
  2. var func = step >= 0 ? new Func<int, int, bool>((a, b) => a >= b) : (a, b) => a <= b;
  3. Func<int, int, bool> func = step >= 0 ? (a, b) => a >= b : (a, b) => a <= b;
Area-Language Design Language-C# Question

Most helpful comment

@leandromoh Because in order to successfully determine type of ternary expression both branches must be of the same type or one must be implicitly convertible to the other. Expressions "target" does not contribute to type inference anywhere in C# as far as I know.
Similar problem:
C# public T GetValue<T>(string name); public void Process(int value); ... Process(GetValue("index")) //Fails to compile even though T could be inferred to be int
However there have been some proposals. I would love to see them implemented.

>All comments

@leandromoh Because in order to successfully determine type of ternary expression both branches must be of the same type or one must be implicitly convertible to the other. Expressions "target" does not contribute to type inference anywhere in C# as far as I know.
Similar problem:
C# public T GetValue<T>(string name); public void Process(int value); ... Process(GetValue("index")) //Fails to compile even though T could be inferred to be int
However there have been some proposals. I would love to see them implemented.

Was this page helpful?
0 / 5 - 0 ratings