Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does C# support type inference of the return type?

This is just a curiousity about if there is a fundamental thing stopping something like this (or correct me if there's already some way):

public TTo Convert<TTo, TFrom>(TFrom from)
{
    ...
}

Called like this:

SomeType someType = converter.Convert(someOtherType);
like image 978
Aaron Anodide Avatar asked Mar 19 '12 02:03

Aaron Anodide


People also ask

Does C have do-while?

The C do while statement creates a structured loop that executes as long as a specified condition is true at the end of each pass through the loop.

What is a do while loop in C?

The do/while loop is a variant of the while loop. This loop will execute the code block once, before checking if the condition is true, then it will repeat the loop as long as the condition is true.


1 Answers

Because what would happen if you did this?

static void M(int x){}
static void M(double x){}
static T N<T>() {}
...
M(N());

Now what is T? int or double?

It's all very easy to solve the problem when you know what the type you're assigning to is, but much of the time the type you're assigning to is the thing you're trying to figure out in the first place.

Reasoning from inside to outside is hard enough. Reasoning from outside to inside is far more difficult, and doing both at the same time is extremely difficult. If it is hard for the compiler to understand what is going on, imagine how hard it is for the human trying to read, understand and debug the code when inferences can be made both from and to the type of the context of an expression. This kind of inference makes programs harder to understand, not easier, and so it would be a bad idea to add it to C#.

Now, that said, C# does support this feature with lambda expressions. When faced with an overload resolution problem in which the lambda can be bound two, three, or a million different ways, we bind it two, three or a million different ways and then evaluate those million different possible bindings to determine which one is "the best". This makes overload resolution at least NP-HARD in C#, and it took me the better part of a year to implement. We were willing to make that investment because (1) lambdas are awesome, and (2) most of the time people write programs that can be analyzed in a reasonable amount of time and can be understood by humans. So it was worth the cost. But in general, that kind of advanced analysis is not worth the cost.

like image 157
Eric Lippert Avatar answered Sep 27 '22 17:09

Eric Lippert