Steven Yates
Steven Yates

Reputation: 2480

dynamic keyword affects return type

I'm not entirley sure why the following code compiles

namespace ConsoleApp13
{
    public class Person
    {

    }
    class Program
    {
        static void Main(string[] args)
        {
            dynamic expand = new ExpandoObject();
            List<Person> people = GetPerson(expand);

        }

        public static Person GetPerson(int item)
        {
            return new Person();
        }

    }
}

Why does the dynamic keyword impact the return type. It's like the compiler give's up on type checking as soon as dynamic is introduced. Is this expected behavior?

Upvotes: 1

Views: 67

Answers (1)

Jon Skeet
Jon Skeet

Reputation: 1504122

Is this expected behavior?

Yes. Almost anything you do that involves a dynamic value ends up with a compile-time type of dynamic. Note that binding is performed dynamically, so even though in this specific case you've only got one GetPerson method, in the more general case of method invocation, overloads could be present at execution time that aren't present at compile-time, with different return types.

There are a few operations which don't end up with a dynamic type:

  • Casting (e.g. (string) dynamicValue)
  • The is operator (e.g. dynamicValue is string)
  • The as operator (e.g. dynamicValue as string
  • Constructor calls (e.g. new Foo(dynamicValue))

Upvotes: 3

Related Questions