Search code examples
c#impromptu-interface

How to access proxied object using impromptu-interface


How can I get access to the Duck Typed proxied object when using impromptu-interface. consider my code that illustrates my example where I get a InvalidCastException when I try to cast my Duck Typed Object to the proxied Object:

using System;
using ImpromptuInterface;

namespace ConsoleApplication1
{
    public class Duck
    {
        public string Says { get; set; }

        public int GetNumberOfQuacksPerMinute()
        {
            return 42;
        }
    }

    public interface IPondBird
    {
        string Says { get; set; }
    }

    class Program
    {
        static void Main(string[] args)
        {
            // Duck says Quack! Quack!! Quack!!!
            var thing = new Duck { Says = "Quack! Quack!! Quack!!!" };

            IPondBird myInterface = Impromptu.ActLike(thing);

            // ...

            // Later on, I want to get access to a proxied object, but I 
            // get a InvalidCastException here
            Duck proxiedObject = (Duck) myInterface;
            Console.WriteLine("Duck # quacks per minute: " 
                + proxiedObject.GetNumberOfQuacksPerMinute());
        }
    }
}

Exception is as follows:

An unhandled exception of type 'System.InvalidCastException' occurred in ConsoleApplication1.exe

Additional information: Unable to cast object of type 'ActLike_IPondBird_c7dd53902ec74f01a3844d4789244ea3' to type 'ConsoleApplication1.Duck'.


Solution

  • You can't. You can think about line

    IPondBird myInterface = Impromptu.ActLike(thing);
    

    As something like

    public class Wrapper : IPondBird 
    {
      public Wrapper(Duck duck) { ... }
    }
    IPondBird myInterface = new Wrapper(thing);
    

    That being said you can make the reference to native object part of the contract itself - like:

    public interface IPondBird
    {
        string Says { get; set; }
        object NativeObject { get; }
    }
    
    public class Duck
    {
        public string Says { get; set; }
    
        public int GetNumberOfQuacksPerMinute()
        {
            return 42;
        }
    
        public object NativeObject { get { return this; } }
    }
    
    IPondBird myInterface = Impromptu.ActLike(thing);   
    var duck = (Duck)myInterface.NativeObject;