Question

...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 :)

Was it helpful?

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.

OTHER TIPS

I think it a point of understanding specific situation in your example it might not make a big difference but it important to consider that dynamic get created at a runtime so you do not have to unbox anything dynamic just take a form of the return type for instance what if instead of doing this you were required not to bind to dynamic but to list

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

List<string> list = CreateMagicList();
list.Add( "lolcat" );

this would work fine since in runtime you bind to same property

but this

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

 List<string> list = CreateMagicList();
    list.Add( "lolcat" );

will give you an error since you have to unbox it

You can return a dynamic, so that in the future, you could actually return a dynamic. With MissingMethodInvoke and MissingPropertyInvoke overloaded. Dynamics are more than just objects.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top