user1839542
user1839542

Reputation: 33

The type or namespace name could not be found keyedcollection

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!

Upvotes: 2

Views: 724

Answers (1)

BoltClock
BoltClock

Reputation: 723729

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);
}

Upvotes: 4

Related Questions