In a dynamic expression dynamic x
, is there a reason/explanation
why the surrounding expression (e.g. foo(x)
) gets dynamic as well?
Consider:
static string foo(object x) { }
static void Main()
{
dynamic x = null;
foo(x); // foo(x) is a dynamic expression
}
I was assuming that the compiler could resolve (at compile time) that foo(object)
is to be called. However, hovering with the mouse over foo(x)
reveals that the type is dynamic instead.
I can help the compiler with the deducing by specifying:
foo((object)x);
but I thought that the type of a dynamic
expression is object
.
The C# Reference does say that "operations that contain expressions of type dynamic are not resolved", my question is:
Are there reasons which prevent the compiler from resolving the type of the "outer"/surrounding expression?
Reference
Type dynamic behaves like type object in most circumstances. However, operations that contain expressions of type dynamic are not resolved or type checked by the compiler. The compiler packages together information about the operation, and that information is later used to evaluate the operation at run time. As part of the process, variables of type dynamic are compiled into variables of type object. Therefore, type dynamic exists only at compile time, not at run time.
https://msdn.microsoft.com/en-us/library/dd264741.aspx
Suppose you had
static string foo(object x) { return "bar"; }
static string foo(string x) { return "foo"; }
static void Main()
{
dynamic x = null;
foo(x); // foo(x) is a dynamic expression
}
In that case the compiler would not be able to resolve the type of the expression. While I think in your example the type should be resolvable it will not be in the cases where it is most useful, making the feature pretty cost ineffective to implement.
In addition, the DLR can't perform any binding on a null reference as in your example.
The reason behind this is that dynamic types are not working with compiler but they are resolved in DLR. There is no way for a compiler to know in to what type your dynamic will be resolved... That's why anything working with dynamic is resolved in run-time only.
More information about DLR : https://msdn.microsoft.com/en-us/library/dd233052.aspx
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With