Method declared with dynamic input parameter and object as return type in fact returns dynamic

namespace ConsoleApplication1
{
  class Program
  {
    static void Main(string[] args)
    {
      var objectGetter = new ObjectGetter();
      var obj = objectGetter.GetItem(); //Visual Studio shows that obj type is System.Object
    }
  }

  public class ObjectGetter
  {
    public object GetItem()
    {
      dynamic dObj = "123";
      var obj = this.Convert(dObj);//Visual Studio shows that obj type is "dynamic" here. why???
      return obj;
    }

    private object Convert(dynamic dObj)
    {
      return new object();
    }
  }
}

I expected that Convert method call will return System.Object but in fact it returns dynamic. I can not understand why.

You can try to use any return type but result will be the same.

Jon Skeet
people
quotationmark

The problem is that you're calling a method with a dynamic argument. That means it's bound dynamically, and the return type is deemed to be dynamic. All you need to do is not do that:

object dObj = "123";
var obj = Convert(dObj);

Then the Convert call will be statically bound, and obj will have a type of object.

From the C# 5 specification, section 7.6.5:

An invocation-expression is dynamically bound (ยง7.2.2) if at least one of the following holds:

  • The primary-expression has compile-time type dynamic.
  • At least one argument of the optional argument-list has compile-time type dynamic and the primary-expression does not have a delegate type.

In this case the compiler classifies the invocation-expression as a value of type dynamic.

people

See more on this question at Stackoverflow