Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I inherit from Dictionary?

I want all the functionality of Dictionary<TKey,TValue> but I want it as Foo<TKey,TValue>.
How should I go about doing this?
Currently I am using

class Foo<TKey,TValue> : Dictionary<TKey, TValue>
{   
    /*
     I'm getting all sorts of errors because I don't know how to 
     overload the constructors of the parent class.
    */
    // overloaded methods and constructors goes here.

    Foo<TKey,TValue>():base(){}
    Foo<TKey,TValue>(int capacity):base(capacity){}

}

What is the right way to overload constructors and methods of the parent class?

NOTE:I think I have misused the word 'overload' please correct it or suggest correction.

like image 899
Pratik Deoghare Avatar asked Oct 20 '09 14:10

Pratik Deoghare


People also ask

Can you inherit from dict Python?

There's no problem with inheriting from dict here because we're not overriding functionality that lives in many different places. If you're changing functionality that's limited to a single method or adding your own custom method, it's probably worth inheriting from list or dict directly.

Does Dictionary guarantee order?

Changed in version 3.7: Dictionary order is guaranteed to be insertion order. This behavior was an implementation detail of CPython from 3.6.

What is IDictionary C#?

The IDictionary<TKey,TValue> interface is the base interface for generic collections of key/value pairs. Each element is a key/value pair stored in a KeyValuePair<TKey,TValue> object. Each pair must have a unique key. Implementations can vary in whether they allow key to be null .


3 Answers

You were close, you just need to remove the type parameters from the constructors.

class Foo<TKey,TValue> : Dictionary<TKey, TValue>
{   
    Foo():base(){}
    Foo(int capacity):base(capacity){}
}

To override a method you can use the override keyword.

like image 189
Jake Pearson Avatar answered Nov 06 '22 23:11

Jake Pearson


Not directly answering your question, just an advice. I would not inherit the dictionary, I would implement IDictionary<T,K> and aggregate a Dictionary. It is most probably a better solution:

class Foo<TKey,TValue> : IDictionary<TKey, TValue>
{   

    private Dictionary<TKey, TValue> myDict;

    // ...
}
like image 22
Stefan Steinegger Avatar answered Nov 06 '22 21:11

Stefan Steinegger


If you just want the same type but with a different name, you can shorten it with using alias:

using Foo = System.Collections.Generic.Dictionary<string, string>;

and then

Foo f = new Foo();
like image 45
Slai Avatar answered Nov 06 '22 22:11

Slai