jm.gunter jm.gunter - 2 months ago 6
C# Question

How to enforce child classes to implement a collection property containing a specific value

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?

Answer

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


    //...
}