c# add property to all derived classes without modify base class

I have base class and multiple derived classes:

record BaseRecord
{
    public int Property1 { get; init; }
    // ...
    public int Property5 { get; init; }
}

record Derived1Record
    : BaseRecord
{
    public int PropertyDerived1 { get; init; }
}

record Derived2Record
    : BaseRecord
{
    public int PropertyDerived2 { get; init; }
}

I need to extend all derived classes with additional properties, but I can’t change base class.
I need something like this:

record DerivedRecordDto<T>
    : BaseRecord
    where T : BaseRecord
{
    // properties from T

    public int PropertyDerivedNew { get; init; }

    public DerivedRecordDto(T record, int propertyDerivedNew)
    {
        // assign all properties from T
        PropertyDerivedNew = propertyDerivedNew;
    }
}

I know I can create new derived class for each current derived class, but this is not very efficient, because number of these classes can be big.

  • Just add a public T Record { get; }?

    – 

  • @Sweeper I need flat structure for future validation logic, without composition, so its not the way

    – 

  • 1

    What “future validation logic”? Why does it need a flat structure? I can think of some solutions but I’m not sure if they will work with whatever “future validation logic” is, so please explain in details what you mean by that.

    – 

  • @Sweeper validation works like this: it walks through each property of each class, take property value by reflection and compare with value from validation rule. Validation rule contains path for that property, for example “Record/PropertyDerivedNew”. So if i move property inner, it will be not found by validation service

    – 




  • 2

    I think this is not possible. Is there any chance you can change the validation logic instead? For example, providing other ways of getting the property value, like calling a method that takes in the property name, or changing the paths in the validation rule.

    – 

Leave a Comment