Search code examples
c#dynamiclanguage-theory

What's the use of returning a dynamic in C#


...compared to plainly returning an object. The magic starts when you assign an object to a dynamic declared variable, so what does returning a dynamic make a difference?

So what is the difference between:

static object CreateMagicList()
{
    return new List<string>();
}

and

static dynamic CreateMagicList()
{
    return new List<string>();
}

They both seem to work exactly the same, in example:

dynamic list = CreateMagicList();
list.Add( "lolcat" );

Note that this is not a practical question. I'm interested in the why part :)


Solution

  • My best guess is that you are allowed to return dynamic so that you could do this:

    private static dynamic Get() {
        return new {X=5};
    }
    public static void Main() {
        var v = Get();
        Console.WriteLine(v.X);
    }
    

    If you could declare Get only as object Get(), then your callers would be forced to replace var with dynamic: otherwise, the code would not compile.

    Same goes for a use case without var:

    public static void Main() {
        Console.WriteLine(Get().X);
    }
    

    without dynamic return type you would have to do an intermediate assignment, or use a cast to dynamic.