Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is the surrounding type of a dynamic expression not statically resolved in C#?

Tags:

c#

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

like image 777
Micha Wiedenmann Avatar asked Jul 07 '15 11:07

Micha Wiedenmann


2 Answers

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.

like image 199
bhh Avatar answered Sep 21 '22 00:09

bhh


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

like image 22
Fabjan Avatar answered Sep 20 '22 00:09

Fabjan