I have a data object which has a base class with three derived classes,
public enum ModelType
{
A,
B,
C
}
public abstract class Parent
{
protected ModelType type;
}
public class ChildA: Parent
{
private new ModelType type = ModelType.A;
}
public class ChildB: Parent
public class ChildC: Parent
The same type field is in the other 2 children with corresponding ModelTypes.
I have another layer between the forms that has some higher level additional information about the data object and an instance of Parent(). I am trying to simplify the problem a lot so I apologise if I am not being clear and have not given enough information.
public enum UIModelType
{
A,
B,
C,
None
}
public class DataObject
{
private Parent someData;
private UIModelType type;
}
The fields have getter and setter properties.
The UI only communicates with the DataObject class and cannot see the lower level someData object.
Now at some point during the UI (which is a wizard to fill in the information in the data objects), the user can select A, B or C. My problem is how to communicate this information without too much code repetition. Right now I have an enum between the UI and DataObject class. So if user selects A, it assigns a data type as A using the enum. The DataObject class now instantiates the someData object with ChildA(). The problem is to communicate between the DataObject and someData object I have another enum with A, B and C to communicate the type.
Would it be healthier to use typeof instead, although I have read that that is not the best way to go.
I need to do many equality checks with the data type (ABC) from the UI all the way to the lower level data object and hence I had thought enums is the fastest way but it doesn’t feel right to have so many enums of the same type in different classes. Am I missing something very obvious here?
Rather than using
typeoforenum, you could useis.However, if I understand your question correctly, it sounds like you’re doing these checks because you need to continually downcast the
someDataobject to provide functionality for theDataObjectclass that depends on the type ofsomeData. If this is the case, you might want to consider refactoring your code, as repeated downcasting can can make code difficult to read and defies some traditional concepts of object-oriented programming.Edit:
Ok, I think I understand your question better, now. You’re looking for a better way of creating children of the
Parentobject (i.e. using the factory pattern) than by using anenum.You could create the instance dynamically based on the type name:
Using an
enummight be easier, but this method allows you to create new subclasses ofParentwithout updating yourenum.If I still missed the point of your question, sorry.