Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Modifying Add in Dictionary: reimplement IDictionary vs inheriting from Dictionary

Tags:

c#

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?")

like image 521
Xavier Peña Avatar asked Dec 25 '22 16:12

Xavier Peña


2 Answers

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.

like image 122
Sriram Sakthivel Avatar answered Apr 09 '23 00:04

Sriram Sakthivel


Short - No reason :) I don't see problems. You have your own implementation of IDictionary. It's ok.

like image 26
Backs Avatar answered Apr 08 '23 23:04

Backs