Reputation: 57
I have an abstract base class with an abstract dictionary property:
public abstract class BaseClass
{
//...
public abstract Dictionary<string, object> Settings { get; set; }
//...
}
I want child classes to implement this property with a particular Key called "Text" (more keys can be added if needed but the "Text" key must be present), e.g.:
public class ChildClass : BaseClass
{
//...
private Dictionary<string, object> _settings = new Dictionary<string, object>()
{
{ "Text", "SomeText" }
};
public Dictionary<string, object> Settings
{
get{ return _settings; }
set{ _settings = value; }
}
//...
}
What's the best way to enforce child classes to not only implement the property but to ensure that it contains a key called "Text" with an associated value?
Upvotes: 1
Views: 139
Reputation: 57
Thanks for the answers. It looks like there is not a good way to enforce the child property to contain a specific key without encapsulating the dictionary in the base class and writing custom get, set methods or writing another class to hold the settings.
As it turns out, in my situation, I only need readonly access to the Settings property so I ended up changing to a protected dictionary property on the base class with a public readonly dictionary wrapper to expose the contents. Then I enforce the setting on the "Text" key via constructor arguments. No abstract properties needed after all.
Upvotes: 0
Reputation: 963
As others have suggested I would hide the implementation of the settings (the dictionary), and expose methods to access the data:
public abstract class BaseClass
{
//...
private readonly Dictionary<string, object> _settings = new Dictionary<string, object>();
protected BaseClass() { }
public object GetSetting(string name)
{
if ("Text".Equals(name))
{
return this.GetTextValue();
}
return this._settings[name];
}
// this forces every derived class to have a "Text" value
// the value could be hard coded in derived classes of held as a variable
protected abstract GetTextValue();
protected void AddSetting(string name, object value)
{
this._settings[name] = value;
}
//...
}
Upvotes: 2
Reputation: 119
I would just make the Settings property non-abstract.
public abstract class BaseClass
{
//...
protected Dictionary<string, object> Settings { get; set; }
public BaseClass()
{
Settings = new Dictionary<string, object>()
{
{ "Text", "SomeText" }
};
}
//...
}
Upvotes: 0