Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c# virtual dictionary?

Tags:

c#

dictionary

I have a class with a dictionary object. Any class that derives from that class, I want to override the dictionary with it's own implementation.

How can this be achieved as the virtual keyword is not valid here?

Thanks.

like image 253
Darren Young Avatar asked Jun 20 '26 22:06

Darren Young


2 Answers

You can't have virtual fields, but you can have virtual properties.

Additionally, it would be a good idea to declare the property-type to be of the IDictionary<TKey, TValue> interface rather than the Dictionary<TKey, TValue> concrete- type, since this class is not designed for inheritance.

E.g:

private readonly Dictionary<string, int> _myDictionary 
                  = new Dictionary<string, int>();

protected virtual IDictionary<string, int> MyDictionary 
{
   get
   {
      return _myDictionary; 
   }
}

Subclasses will not see the field; only the property will be visible. They are free to override the property and provide their own implementation; for example by returning an instance of a custom-type that implements the interface.

like image 89
Ani Avatar answered Jun 22 '26 10:06

Ani


Something like this should work:

public class Base
{
    private Dictionary<string, string> dictionary = new Dictionary<string, string>();

    public virtual IDictionary<string, string> DictInstance
    {
        get { return this.dictionary; }
    }
}

public class Derived : Base
{
    private MySpecialDictionary otherDictionary = new MySpecialDictionary();

    public override IDictionary<string, string> DictInstance
    {
        get { return this.otherDictionary; }
    }
}
like image 36
Simon Steele Avatar answered Jun 22 '26 10:06

Simon Steele



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!