Duck Typing in Aspnet vNext

One of the cool new features announced as part of aspnet vnext is Assembly Neutral Interfaces. Assembly Neutral Interfaces allow you to define identical interfaces in multiple assemblies and then treat then as one interface. In other words Duck Typing.

Many people say that seeing is believing, but of course as developers we know that playing is believing, So I decided to play with it.

I created a new Aspnet vNext console application and 2 Aspnet vNext class libraries. In each library I put the following code file.

namespace DuckTypes.Types
{
    [AssemblyNeutral]
    public class AssemblyNeutralAttribute : Attribute { }

    [AssemblyNeutral]
    public interface IMyType
    {
        string Get();
    }

    public class MyType : IMyType
    {
        public string Get()
        {
            return "Got";
        }
    }
}

Except that in the second file I called the class MyType2 and the Get method returned “Got2”. I then created an array of IMyType and put and instance of each in it, and output type.Get() to the console.

IMyType[] types = new IMyType[] { new MyType(), new MyType2() };

foreach (var type in types)
{
    Console.WriteLine(type.Get());
}

 

Visual Studio had a fit about this

vs_errors_assembly_neutral_interfaces

But it works

console_assembly_neutral_interfaces

I think I’ll run some performance tests to see how it compares to regular referenced interfaces.

Leave a Reply