2

I'm fairly new to C# so forgive me if this is a stupid question. I'm experiencing an error but I do not know how to resolve it. I'm using Visual Studio 2010.

This code line

public class GClass1 : KeyedCollection<string, GClass2>

Gives me the error

'GClass1' does not implement inherited abstract member 'System.Collections.ObjectModel.KeyedCollection<string,GClass2>.GetKeyForItem(GClass2)'

From what I've read this can be resolved by implementing the abstract member in the inherited class like so

public class GClass1 : KeyedCollection<string, GClass2>
{
  public override TKey GetKeyForItem(TItem item);
  protected override void InsertItem(int index, TItem item)
  {
    TKey keyForItem = this.GetKeyForItem(item);
    if (keyForItem != null)
    {
        this.AddKey(keyForItem, item);
    }
    base.InsertItem(index, item);
}

However this gives me errors saying 'The type or namespace name could not be found TKey/TItem could not be found.'

Help!

1 Answers1

4

TKey and TItem are the type parameters of KeyedCollection<TKey, TItem>.

Since you're inheriting from KeyedCollection<string, GClass2> with the concrete types string and GClass2 respectively, you're supposed to replace the placeholder types TKey and TItem in your implementation with those two types:

public class GClass1 : KeyedCollection<string, GClass2>
{
  public override string GetKeyForItem(GClass2 item);
  protected override void InsertItem(int index, GClass2 item)
  {
    string keyForItem = this.GetKeyForItem(item);
    if (keyForItem != null)
    {
        this.AddKey(keyForItem, item);
    }
    base.InsertItem(index, item);
}
BoltClock
  • 700,868
  • 160
  • 1,392
  • 1,356
  • That works great. However another error has popped up. This time its related to the previous "fix". I forgot that GetKeyForItem is protected. The new error tells me that I can't change access modifiers when overriding System.Collections.ObjectModel.KeyedCollection.GetKeyForItem(GClass2) – user1839542 Nov 20 '12 at 18:00
  • Change it back. You should probably also implement `GetKeyForItem()` - I just realized there isn't any implementation (taking from your example code)... – BoltClock Nov 20 '12 at 18:18