I am trying to write a Color Theme class that has a main property ForeColor and BackColor (for example). There are several child classes that have other properties, but I want those child classes to return the default ForeColor of its parent class if it’s not set.
The idea is that for some specific control colors you can set them if you want otherwise the class will return that I believe is the best alternative.
I am having troubles on accessing the parent class properties and clearly I can’t figure this one out, something like this…
public class Theme {
public Color GenericForeColor;
public Color GenericBackColor;
public TabControlTheme TabControls = new();
public class TabControlTheme {
public Color ActiveForeColor;
get => ActiveForeColor == Color.Empty ? parent.GenericForeColor : ActiveForeColor;
set => ActiveForeColor = value;
}
}
>Solution :
You can add a constructor the TabControlTheme
class and pass the parent as an argument.
public class Theme
{
public Color GenericForeColor;
public Color GenericBackColor;
public TabControlTheme TabControls;
public Theme()
{
TabControls = new TabControlTheme(this); // pass this Theme as parent
}
public class TabControlTheme
{
private readonly Theme parent;
public TabControlTheme(Theme parent)
{
this.parent = parent ?? throw new ArgumentNullException(nameof(parent));
}
public Color ActiveForeColor;
get => ActiveForeColor == Color.Empty ? parent.GenericForeColor : ActiveForeColor;
set => ActiveForeColor = value;
}
}