views:

519

answers:

2

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.

+6  A: 

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.

Jake Pearson
Not within the constructors, no... they're already within the type, so they already "have" the type parameters.
Jon Skeet
Nope, TKey and TValue are now defined as part of the class. You don't need to redefine them in each method.
Jake Pearson
_and_ make them public, usually.
Henk Holterman
Sorry,I deleted the comment by accident.
TheMachineCharmer
How can I make them all public without writing public in front of each one?
TheMachineCharmer
I tried with c++ syntax but it doesn't seem to work.
TheMachineCharmer
public has to be explicitly defined in C#, without it everything defaults to private.
Jake Pearson
I guess then I will have to override each and every constructor of the base class explicitly or is there any other way ?
TheMachineCharmer
Not quote everything defaults to private: class, struct and enum default to internal, whereas methods, properties and fields default to private.
ShellShock
+4  A: 

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;

    // ...
}
Stefan Steinegger
(+1) What do you recommend if I want to use just the Dictionary but with name Foo?
TheMachineCharmer
Why would you do this? A kind of C-style typedef?
Stefan Steinegger
That's a Decorator (http://en.wikipedia.org/wiki/Decorator_pattern). Possible drawback: You need to implement each connection from your class to your member dictionary manually.
The Chairman
@Mao: that's true, you need to implement each method, but you also might find it practical to have full control.
Stefan Steinegger