raklos
raklos

Reputation: 28545

Change the type on a Subclass property

I'm unsure how I would do this. I have a common base class that is a DTO that has the majority of the properties I need. This class has some properties that are base classes too.

I want to be able to have additional properties depending on the circumstance:

E.g

 public class BaseOrder
 {
     //Other common properties
     public List<BaseItem> Items { get; set; }
 }
 
 public class BaseItem
 {
     //Properties to do with an Item
 }
 
 public class AdminOrder: BaseOrder
 {
     // THIS IS THE KEY PART: I want Items to be a list of type AdminItem
     public List<AdminItem> Items { get; set; }
 }
 
 public class AdminItem:BaseItem
 {
     //Properties to do with an Item AND Admin stuff too
 }

How can I do this?

Upvotes: 0

Views: 185

Answers (2)

gunr2171
gunr2171

Reputation: 17544

Use generic arguments for the BaseOrder class to specify the type of the Items property, and limit it to a type that is or inherits from BaseItem.

You can then remove the property completely in AdminOrder, because it's inherited with the type specified in the generic arguments.

 public class BaseOrder<TItem> where TItem : BaseItem
 {
     //Other common properties
     public List<TItem> Items { get; set; }
 }
 
 public class BaseItem
 {
     //Properties to do with an Item
 }
 
 public class AdminOrder: BaseOrder<AdminItem>
 {
     // No need to define Items again here!
 }
 
 public class AdminItem:BaseItem
 {
     //Properties to do with an Item AND Admin stuff too
 }

You don't need to have with TItem : BaseItem, but it helps enforce choosing the right type in AdminOrder.

Also optional, you may consider making BaseOrder abstract, if you don't want a BaseOrder object directly being created - you only expect a type that inherits from BaseOrder.

Upvotes: 3

lkovalyk
lkovalyk

Reputation: 66

public class BaseOrder<TYPE> where TYPE: BaseItem
 {
     //Other common properties
     public List<TYPE> Items { get; set; }
 }
 
 public class BaseItem
 {
     //Properties to do with an Item
 }
 
 public class AdminOrder: BaseOrder<AdminItem>
 {
 }
 
 public class AdminItem:BaseItem
 {
     //Properties to do with an Item AND Admin stuff too
 }

Upvotes: 5

Related Questions