Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Problems with dynamic parameter

Tags:

c#

.net

dynamic

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?

like image 644
Alexander Leyva Caro Avatar asked Nov 06 '14 13:11

Alexander Leyva Caro


1 Answers

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);
like image 140
Selman Genç Avatar answered Oct 04 '22 05:10

Selman Genç