Does C # type support return type?

This is just curiosity if there is a fundamental thing stopping something like this (or correct me if there is some way):

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

Called as follows:

 SomeType someType = converter.Convert(someOtherType); 
+6
source share
3 answers

Because what happens if you do 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 very easy to solve a problem when you know what type you are assigning, but most of the time that you are assigning is what you are trying to figure out first

Reasoning from the inside out is quite complicated. Reasoning from the outside to the outside is much more complicated, and to do both at the same time is extremely difficult. If it is difficult for the compiler to understand what is happening, imagine how difficult it is for a person to try to read, understand and debug code, when conclusions can be drawn from both the type and the context of the expression. This conclusion makes programs more difficult to understand, and not easier, so it would be nice to add it to C #.

Now, with that, C # supports this function with lambda expressions. When faced with an overload resolution problem in which a lambda can be connected in two, three, or millions of different ways, we link it in two, three, or millions of different ways, and then evaluate these millions of different possible bindings to determine which one is β€œBest " This does overload at least NP-HARD in C #, and it took me most of the year to implement. We were ready to make these investments because (1) lambdas are amazing, and (2) most of the time people write programs that can be analyzed in a reasonable amount of time and can be understood by people. So it was worth it. But overall, such an extended analysis is not worth the cost.

+21
source

C # expressions always * have a fixed type, regardless of their environment.

You request an expression whose type is determined by what it assigned; what violates this principle.

*), with the exception of lambda expressions, functional groups, and the null literal.

+1
source

Unlike Java, a reference to a C # type is not based on a return value type. And don't ask me why Eric Lippert answered these questions "why can't C # ...":

because no one has ever designed, defined, implemented, documented, and sent this function

0
source

Source: https://habr.com/ru/post/911060/


All Articles