Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

var is not detecting result of method with dynamic input

Tags:

c#

var

dynamic

I have the following problem

private int GetInt(dynamic a)
{
    return 1;
}

private void UsingVar()
{
    dynamic a = 5;
    var x = GetInt(a);
}

But x is still dynamic. I don't understand why.

Wrong type

like image 502
Max Weber Avatar asked Mar 03 '23 00:03

Max Weber


1 Answers

Since your argument a in the GetInt method call have the type dynamic, so the overload resolution occurs at run time instead of at compile time.

Based on this:

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.

Actually by using the dynamic you are using the late binding (defers to later), and it means, the compiler can't verify it because it won't use any static type analysis anymore.

The solution would be using a cast like this:

var x = (int)GetInt(a);

The following is how the compiler is treating your code:

private void UsingVar()
{
    object arg = 5;
    if (<>o__2.<>p__0 == null)
    {
        Type typeFromHandle = typeof(C);
        CSharpArgumentInfo[] array = new CSharpArgumentInfo[2];
        array[0] = CSharpArgumentInfo.Create(CSharpArgumentInfoFlags.UseCompileTimeType, null);
        array[1] = CSharpArgumentInfo.Create(CSharpArgumentInfoFlags.None, null);
        <>o__2.<>p__0 = CallSite<Func<CallSite, C, object, object>>
           .Create(Microsoft.CSharp.RuntimeBinder.Binder
           .InvokeMember(CSharpBinderFlags.InvokeSimpleName, "GetInt", null, typeFromHandle, array));
    }
    object obj = <>o__2.<>p__0.Target(<>o__2.<>p__0, this, arg);
}
like image 93
Salah Akbari Avatar answered Mar 17 '23 02:03

Salah Akbari