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.
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.
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; }
}
}
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