When passing a dynamic method, the result is a dynamic expression, even if it is not

In C # 5, when I tried to pass a dynamic parameter to a method, the result somehow became dynamic.

class Program { static void Main(string[] args) { dynamic value = "John"; Find<int>(value).ToList(); } public static IEnumerable<T> Find<T>(object value) { //SOME LOGIC yield return default(T); //REAL RESULT } } 

Find<T>(value) should return an IEnumerable<T> . Why does the compiler consider dynamic?
I know that Find<int>(val as object).ToList(); solves this, but I want to understand WHY .

+2
source share
2 answers

Since there may be a Find that matches a different method than your run-time search, as soon as you start dynamic, everything is dynamic, including deciding which method is suitable, since only something is dynamic in the expression, the whole expression is dynamic .

For example, there may be another method, for example

 public static T Find<T>(sometype value) { return default T; } 

This would be a better match at runtime if the dynamics were of the type sometype, therefore, if the compiler does not know which dynamics cannot deduce the type of the return value, since this type can return a method that matches the best AT RUNTIME.

So, the compiler says that it returns dynamic, because it is best, your method returns something else, but the compiler does not yet know whether this method will be called.

+3
source

the dynamic type is unknown at compile time, but at runtime. Thus, at run time, it may be a string type, and there may be a better match with the name Find (string value), which returns a different type. This is the reason the compiler cannot tell you. It is allowed at runtime.

0
source

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


All Articles