Suraj
Suraj

Reputation: 36547

Is it possible to create a type with two properties having the same name?

According to the documentation, Type.GetProperty(string, BindingFlags) throws AmbiguousMatchException when:

More than one property is found with the specified name and matching the specified binding constraints

I'm looking for an example type where the GetProperty method would throw because more than one property is found with the same name. I created an inheritance relationship (A : B) where both classes define the same named public property (using the new keyword), with BindingFlags = Public | Instance, but that doesn't throw.

Upvotes: 2

Views: 784

Answers (3)

madreflection
madreflection

Reputation: 4947

In C#, a class can implement multiple indexers, all of which are called Item.

public class Class1
{
    public string this[int firstParameter]
    {
        get { return ""; }
    }

    public string this[string firstParameter, int secondParameter]
    {
        get { return ""; }
    }
}

Then you can produce the exception using this:

class Program
{
    static void Main()
    {
        // This will throw AmbiguousMatchException:
        typeof(Class1).GetProperty("Item", BindingFlags.Public | BindingFlags.Instance);
    }
}

That will produce the AmbiguousMatchException with a single class and the Public and Instance binding flags.

Upvotes: 4

Guru Stron
Guru Stron

Reputation: 142123

You can get ambiguous match if you'll play with BindingFlags. For example BindingFlags.IgnoreCase allows you to get this exception despite not having properties with the same name:

class MyClass
{
    public string MyProperty {get; set;}    
    public int Myproperty {get; set;}
}

typeof(MyClass).GetProperty("MyProperty", BindingFlags.Public | BindingFlags.Instance | BindingFlags.IgnoreCase)

Also next set up with BindingFlags.FlattenHierarchy produces the mentioned error:

class MyClass : Base
{
    public new string MyProperty { get; set; }
}

class Base
{
    public static string MyProperty {get;set;}
}

typeof(MyClass).GetProperty("MyProperty", 
    BindingFlags.Static | BindingFlags.Instance | BindingFlags.Public | BindingFlags.FlattenHierarchy);

Upvotes: 3

Christian Held
Christian Held

Reputation: 2828

This is an example using BindingFlags.FlattenHierarchy that leads to a name clash between a static and instance property.

public  class Program
{
    public class A
    {
        public static string Property { get; set; }
    }

    public class B : A
    {
        public string Property { get; set; }
    }

    public static void Main(string[] args)
    {
        var type = typeof(B);
        var property = type.GetProperty(
            "Property",
            BindingFlags.Public |
            BindingFlags.Static |
            BindingFlags.Instance |
            BindingFlags.FlattenHierarchy);
    }
}

Upvotes: 3

Related Questions