Tutorial :How would you approach this design?



Question:

I have ControlA which accepts an IInterfaceB which has a property of type List<unknownType>

In an event of ControlA i need to add a new instance of unknownType to the List in IInterfaceB...

unknownType needs specific properties so i immediately thought it could be an interface, but quickly realised interfaces cannot be instantiated...

How would you design this system?

EDIT the current inheritance chain looks like this:

topLevelClass -> baseObject -> IBaseObject (which is implemented in topLevelClass)  

so if i added a new class to the chain it would need to do the inheriting and implementing which would be impossible (afaik)


Solution:1

If I'm interpreting this correctly, you could add a constraint on unknownType to be of some interface that contains the properties you need:

class ControlA  {      void Frob<T>(IInterfaceB<T> something) where T : IHasSomeProperties, new()      {          something.ListOfT.Add(new T() { SomeProperty = 5 });          something.ListOfT.Add(new T() { SomeProperty = 14 });      }  }  


Solution:2

Would a restriction on the type work?

List<T> where T : IInterface  


Solution:3

Your specification isn't specific enough to answer well, but try putting constraints on T.

public interface IInterfaceB<T>      where T : new()  {      List<T> Whatever { get; }  }  

This allows you to do this:

T iDoNotCare = new T();  


Solution:4

Why does List have to be an unknowntype? Why can't it be a real class, the has the real properties you need with a constructor for you to instantiate? If you need to extend that class, you can then inherit from it. Based on the information you're providing, if all you need is a few properties in the class that goes into this List, then a good old class should do the trick.


Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Previous
Next Post »