Alexander Leyva Caro
Alexander Leyva Caro

Reputation: 1253

Problems with dynamic parameter

I have this function

string F(dynamic a)
{
    return "Hello World!";
}

later when i say

dynamic a = 5;
var result = F(a);

result must be in compilation time a string type, but that not happened, why? In fact, the compilar pass this

int result2 = F(a);

and not this

int result3 = F(5);

Anything help please?

Upvotes: 5

Views: 542

Answers (1)

Selman Genç
Selman Genç

Reputation: 101681

It is explained in here:

Overload resolution occurs at run time instead of at compile time if one or more of the arguments in a method call have the type dynamic, or if the receiver of the method call is of type dynamic.

Now in the case of F(a) since a is dynamic, compiler doesn't check for the overloads at compile-time. But when you say:

F(2);

2 is an integer and not dynamic. That's why the overload resolution occurs at compile time and you get the error.If you cast the integer literal to dynamic you won't get any error at compile time (but you do on run-time):

int x = F((dynamic)2);

Upvotes: 7

Related Questions