2

I have some legacy code to be refactored. At first, I have a child class interface: IChild. and some classes that implements that interface, like: ChildType1 : IChild, ChildType2 : IChild and ChildType3 : IChild.

The parent has the child types properties, and each time only one of them get initialized example if ChildType1 has value then ChildType2 and ChildType3 are null:

class Parent
{
    public ChildType1 Type1 { get; set; }
    public ChildType2 Type2 { get; set; }
    public ChildType3 Type3 { get; set; }
    //...
}

The IChild holds some important property Enum:

public interface IChild
{
    ImportantEnum MyEnum { get; set; } 
    //
}

My question: regarding the fact I do not know which one of the Types are initiated, what is the best way to make the child MyEnum property to be available through the parent api?

I'm open for refactoring.

Shahar Shokrani
  • 7,598
  • 9
  • 48
  • 91

2 Answers2

2

Seems to me like you need to change your Parent class - and it looks, based on the information you've provided so far, that this is a perfect candidate for the use of generics:

class Parent<TChild> where TChild : IChild
{
    public TChild Child { get; set; }
}
Zohar Peled
  • 79,642
  • 10
  • 69
  • 121
  • What is the name for this design pattern?? – Shahar Shokrani Oct 23 '18 at 05:10
  • This is not a design pattern, it's a .Net framework capability as old as .Net 2.0. It's just called Generics. You can read all about it in [official documentation.](https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/generics/) – Zohar Peled Oct 23 '18 at 06:07
1

I would refactor it so that you directly expose the current IChild instance, from which it is trivial to query for MyEnum.

class Parent
{
    Public IChild Child { get; set; }
}
...
Parent p = new Parent();
IChild child = p.Child;
Type childType = p.Child.GetType();
ImportantEnum val = child.MyEnum