DynamicObject.TryConvert not called when casting to interface type

Viewed 5288

The following code throws an exception. TryConvert is not being called for the cast to interface. Why is this? Can I work around the problem?

using System.Dynamic;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            dynamic test = new JsonNull();
            var ok = (string)test;
            // Next line throws:
            // Unable to cast object of type 'ConsoleApplication1.JsonNull' to type 'ConsoleApplication1.IFoo'.
            var fail = (IFoo)test;
        }
    }

    class JsonNull : DynamicObject
    {
        public override bool TryConvert(ConvertBinder binder, out object result)
        {
            result = null;
            return !binder.Type.IsValueType;
        }
    }

    interface IFoo { }
}
3 Answers

I've found that if you change this line:

var fail = (IFoo)test; 

to this:

IFoo success = test;

it works as expected.

It seems that only an implicit conversion works in this case. Looks like a bug to me.

I also find it very annoying that this fails as well:

class Program {
  static void Main(string[] args) {
    dynamic test = new JsonNull();
    Fails(test);
  }
  static void Fails(IFoo ifoo) { }
}
// ...

Because it looks like it should use an implicit conversion too. Another bug?

Related