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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With