views:

100

answers:

1

I need to create a type that has two properties with the same name, and only differ on return type. Dynamically emitting this type via reflection is perfectly acceptable.

Something like this:

public TypeA Prop { get; }
public TypeB Prop { get; }

I do understand that I cannot consume this property from C# or VB.NET or lots of other .NET languages.

To prevent answers that explain to me why I don't want to do this, let me explain why I need it: I need it to reproduce a bug.

More specifically, I have a bug in AutoFixture where a Moq of a type will cause it to throw an exception in certain cases. The problem is that the type emitted by Moq contains two properties both named 'Mock' that differ only on the return type.

I would like to reproduce this scenario in a unit test, but I'd rather not take a dependency on Moq just for that single reason, so I'd like to reproduce the behavior internally in the test suite.

+6  A: 

You can have 2 properties with the same name that differ only by the type, and you can do that without dynamically emitting the type :

class Foo
{
    public string X
    {
        get { return "Hello world"; }
    }
}

class Bar : Foo
{
    public new int X
    {
        get { return 42; }
    }
}

void Main()
{
    foreach(PropertyInfo prop in typeof(Bar).GetProperties())
    {
     Console.WriteLine("{0} : {1}", prop.Name, prop.PropertyType);
    }
}

The output of this code will be :

X : System.Int32
X : System.String

Thomas Levesque
That was excactly what I needed to reproduce the bug. Thanks a lot :)
Mark Seemann