So let's say that I need to redefine Add
in my Dictionary<string, string>
.
Solution A:
public class ImplementedDict : IDictionary<string, string>
{
private readonly Dictionary<string, string> _data = new Dictionary<string, string>();
public void Add(string key, string value)
{
_data.Add(key, value);
}
}
Solution B:
public class InheritedDict : Dictionary<string, string>
{
public override void Add(string key, string value)
{
base.Add(key, value);
}
}
Another StackOverflow user was telling me (in another thread's comments section) that solution A is the right one. Which is the contrary of what I expected.
Apparently it is because "Add isn't a virtual method". He was pointing me to the documentation: https://msdn.microsoft.com/en-us/library/k7z0zy8k(v=vs.110).aspx
I confess that I still don't get it.
Edit: so the question is: why would solution B be considered bad code? (sorry, @Backs's answer made sense when I wrongly asked "why would solution A be considered bad code?")
When you shadow a method, if the client code calls the method with instance typed as base class, then your method will not be called. It will call base class method.
This is the main reason why you're suggested to use method1.
For example:
Dictionary<string, string> dic = new InheritedDict();
dic.Add("key","value");//Will not call your method.
If the Add
method was declared virtual(it isn't), you could have overridden the Add
method. In that case it will call the derived class method as you expect.
Short - No reason :) I don't see problems. You have your own implementation of IDictionary. It's ok.
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