1

Hi I have just been struggling with how to inherit and extend properties in the child class' nested class from the parent class' nested class. Example Below:

public class AttributeViewModel{
   //Common Properties...

   public AttributeViewModelSettings Settings {get; set;}

   public class AttributeViewModelSettings {
     //Common Settings
   } 
}

public class ListAttributeViewModel : AttributeViewModel {
   //List specific properties...

   public ListAttributeViewModelSettings Settings { get; set; }

   public class ListAttributeViewModelSettings : AttributeViewModelSettings {
     //Settings Specific to Child Class
   }
}

We are doing this as we are not yet sure which settings will be needed for each of the possible attributes the user can select. Doing it this way would allow us to change those settings easily but I just cannot figure out the right way to approach something like this.

1 Answer 1

1

If i understood your issue correctly you can try to use generics:

public abstract class AttributeViewModelBase
{
    public abstract AttributeViewModelSettings BaseSettings{ get; }
    public class AttributeViewModelSettings
    {
        //Common Settings
    }

}
// Define other methods, classes and namespaces here
public class AttributeViewModel<T>: AttributeViewModelBase 
    where T: AttributeViewModelBase.AttributeViewModelSettings
{
    //Common Properties...
    public override AttributeViewModelSettings BaseSettings => Settings;
    public T Settings { get; set; }

}

public class ListAttributeViewModel : AttributeViewModel<ListAttributeViewModel.ListAttributeViewModelSettings>
{
    //List specific properties...

    public ListAttributeViewModelSettings Settings { get; set; }

    public class ListAttributeViewModelSettings : AttributeViewModelSettings
    {
        //Settings Specific to Child Class
    }
}
Sign up to request clarification or add additional context in comments.

2 Comments

I basically just typed up this exact answer on my phone to the surprise someone beat me to it. Though I didn't have the abstract property as T Settings should suffice
@pinkfloydx33 Thought it would be convenient in some edge cases so decided to add it=)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.