Search code examples
c#.netsolid-principles

C# SOLID - Extend class and override/hide members without violating Open/Closed?


I need to extend a class where the child class will not use some members of the parent class. How should the unused members be handled and still respect the open/closed SOLID principle? I'm considering doing something like the code below, but existing code that uses reflection will get exceptions. If I put data in the deprecated members, existing code will produce unexpected results.

I feel that a totally different approach should probably be used. How to handle this situation without modifying existing code (which would also violate the open/closed principle)?

class Parent
{
    public virtual int myVarMin { get; set; } = 0;
    public virtual int myVarMax { get; set; } = 10;
    public int myVar { get; set; }
    public int unchanged1 {get; set;}
    //.
    //numerous other members that are irrelevant to the question
    //.
    public void doSomething(){/*do something*/}
    //
}

class Child:Parent
{
    //considered impementation from original question 
    public override int myVarMin => throw new NotSupportedException();
    public override int myVarMax => throw new NotSupportedException();
    public List<int> myVarList = new List<int>();
}

class MyExistingCode
{
    public void Display(Parent parent)
    {
        foreach (var info in parent.GetType().GetProperties())
        {
            Console.WriteLine($"{info.Name}: {info.GetValue(parent)}");
        }
    }
}

Solution

  • I ended up doing something like this (the Parent and MyExistingCode classes were unchanged, so they comply with the open/closed principle):

    class Child : Parent
        {
            public new int? myVarMin => null;
            public new int? myVarMax => null;
            public List<int> myVarList = new List<int>();
        }
    
     class MyNewCode : MyExistingCode
        {
            public new void Display(Parent parent)
            {
                foreach (var info in parent.GetType().GetProperties())
                {
                    Console.WriteLine($"{info.Name}: {info.GetValue(parent) ?? "NULL"}");
                }
            }
        }
    

    I was surprised that I could hide an int with an int? without an error. I will Accept another answer if it is better.