David DeMar
David DeMar

Reputation: 2670

Can't use certain methods when extending SortedList

I have a class that extends SortedList. I can use the many of the SortedList methods in my class like Add() and Remove() but for some reason it doesn't like it when I try to use GetKey(). Can anyone tell me why this might be happening?

public class SymbolTableImplementation : SortedList<string, SymbolTableEntry>, SymbolTable
{
    public SymbolTableEntry Enter(string name)
    {
        SymbolTableEntry entry = SymbolTableFactory.CreateSymbolTableEntry(name, this);
        Add(name, entry);  // This is OK
        return entry;
    }

    //  Look up an existing symbol table entry. Null if it does not exist.
    public SymbolTableEntry Lookup(string name)
    {
        return GetKey(name);  // Doesn't exist in current context
    }
}

Upvotes: 0

Views: 597

Answers (3)

Hans Passant
Hans Passant

Reputation: 942040

No GetKey(), that's already clear. The proper implementation is:

public SymbolTableEntry Lookup(string name)
{
    return this[name];
}

Which should give you pause, the method is superfluous. The indexer of SortedList is already good enough to get the job done. So just remove this method, the user of this class won't be able to guess which one to use.

Note that there's a similar problem with Add() vs Enter(). Nothing good will happen when the client programmer uses Add(). What you really want to do is replace or hide the Add() method but that's not possible. You can overload it but that's as far as that can go.

The .NET collection classes are not really designed to be derived from, their methods are not virtual. They work better if you encapsulate them, creating your own collection class that only inherits, say, IDictionary and use a private SortedList to get the job done. That's a fair amount of work but it will be squeaky clean.

Upvotes: 2

Kirk Woll
Kirk Woll

Reputation: 77586

GetKey is defined in SortedList, which is actually a completely separate class from SortedList<TKey, TValue>. You also have a mistake in your original code; if you were actually using GetKey/SortedList, this would not have compiled:

return GetKey(name);

Instead, just use the IDictionary indexer:

return this[name];

Upvotes: 3

Kirill Polishchuk
Kirill Polishchuk

Reputation: 56182

There is no method with name GetKey in SortedList<TKey, TValue> class.

Upvotes: 2

Related Questions