5

I'm trying to rename my indexer property using IndexerName attribute on my abstract classes. But it still show compilation error The type 'XXX' already contains a definition for 'Item'.

Abstract class:

public abstract class MyAbstract
{
    [IndexerName("Indexer")]
    public abstract string this[string propertyName]
    {
        get;
    }
}

Concrete class:

public class MyConcrete : MyAbstract
{
    string item;

    public string Item
    {
        get { return item; }
        set { item = value; }
    }

    public override string this[string propertyName]
    {
        get { return propertyName; }
    }
}

Compilation error:

The type 'MyConcrete' already contains a definition for 'Item'.

I've tried to put IndexerName on indexer override and it show error "Cannot set the IndexerName attribute on an indexer marked override"

How to use IndexerName on abstract classes ?

Thanks in advance.

Jalal Said
  • 15,906
  • 7
  • 45
  • 68
Steven Suryana
  • 179
  • 1
  • 2
  • 15

2 Answers2

2

The issue will be fixed if you just rename the Item to something else, also consider checking this related issue on IndexerName at here and here.

Community
  • 1
  • 1
Jalal Said
  • 15,906
  • 7
  • 45
  • 68
  • having to rename the property is just what he is trying **not** to do, hence the usage of the `IndexerName` attribute – BrokenGlass Aug 10 '11 at 02:24
  • @BrokenGlass is correct, i don't want to rename `Item`. Thanks jalal.. I've checked the articles. It seems clear to me that there's no solution other than having my property renamed. – Steven Suryana Aug 10 '11 at 02:58
  • @Steven: Sorry, that is what comes to my mind right now, if I find someway out I will notify you. – Jalal Said Aug 10 '11 at 03:03
  • 2
    @Jalal Don't mind.. it sucks that microsoft using common word like "Item" to define an automatic property --". – Steven Suryana Aug 10 '11 at 03:21
2

It seems that the compiler checks the naming before applying attributes inheritance. From the declaration of IndexerNameAttribute we can see it can be inherited to derived classes. It makes more sense if the compiler checks the naming after inherited attributes are ready, since attributes can probably affect the names. Maybe there are some reasons that the compiler team decides to check naming first, I don't know. It's not your fault but I think to resolve the issue you need to change the name of the property Item(even I know you are trying not to).

[AttributeUsage(AttributeTargets.Property, Inherited = true)]
public sealed class IndexerNameAttribute : Attribute

Another alternative solution is using real methods instead of indexers.

//base abstract class
public abstract string GetItem(string propertyName);
//and implement it in the derived classes
Cheng Chen
  • 42,509
  • 16
  • 113
  • 174