简体   繁体   中英

C# dynamic parameter of a function changes it return type

A simple code

dynamic v = "";
var a = F("");
var b = F(v);

static bool F(dynamic o) => true;

the type of variable a is bool, but b is dynamic instead of bool, why?

The think the short answer is that once you declare a dynamic , the dynamic "behavior" (?) will continue to propagate through all future references to it until you explicitly resolve it.

It's not that the return type of F(o) has changed, it's that the compiler simply doesn't care anymore.

The declaration of a dynamic variable has disabled compile-time type-checking for all future references to that variable...again, until (or unless) it's explicitly resolved.

I am looking forward to reading other explanations, however.

The initial assertion that “the type of variable a is bool, but b is dynamic instead of bool” is not correct for a valid C# compiler, nor is it illustrated with the code.

The following program will fail to compile, showing that b is indeed a bool See https://dotnetfiddle.net/E6fn0P to run the code.

using System;
                    
public class Program
{
    public static void Main()
    {
        static bool F(dynamic o) => true;
        
        dynamic v = "";
        var a = F("");
        var b = F(v);
        _ = b.Foo;

        Console.WriteLine("Hello World");
    }
}

The expected compiler error is:

Compilation error (line 12, col 13): 'bool' does not contain a definition for 'Foo' and no accessible extension method 'Foo' accepting a first argument of type 'bool' could be found (are you missing a using directive or an assembly reference?)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM