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.
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.
Changed in version 3.7: Dictionary order is guaranteed to be insertion order. This behavior was an implementation detail of CPython from 3.6.
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 .
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.
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;
// ...
}
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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With