Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

C# return parent class value from child class?

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…

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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;
  }
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading