Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Item and this[] - Member with the same name is already declared [duplicate]

Possible Duplicate:
Class with indexer and property named “Item”

Just came across something I've not seen before and was wondering why this might be happening?

With the following class, I get the compiler error "Member with the same name is already declared" with respect to "Item" and "this[...]".

public class SomeClass : IDataErrorInfo 
{
    public int Item { get; set; }

    public string this[string propertyName]
    {
        get
        {
            if (propertyName == "Item" && Item <= 0)
            {
                return "Item must be greater than 0";
            }
            return null;
        }
    }

    public string Error
    {
        get { return null; }
    }
}

The compiler seems to think that this[...] and Item are using the same member name. Is this correct / normal? I am surprised I have not come across this before.

like image 838
Mike Rowley Avatar asked Jan 25 '26 07:01

Mike Rowley


1 Answers

When you define the indexer like this:

this[string propertyName]

It is compiled into the .Item property.

You can fix that with [System.Runtime.CompilerServices.IndexerName("NEW NAME FOR YOUR PROPERTY")] attribute to your indexer.

like image 179
VMAtm Avatar answered Jan 26 '26 19:01

VMAtm