Ahndheekee
Ahndheekee

Reputation: 11

Type of a certain class

I am wondering whether there is way to limit the Type variable to a certain class only. For example

    public class Product
    {
       public string Name;
       public bool Install;

       public List<Type> Components;
       public List<Type> Prerequisite;
    }

If the List can be specified to be of typeof(Product) and its derivatives, I think it will make my generic design much more straightforward and easy to use. Maybe like so:

    public class Product
    {
       public string Name;
       public bool Install;

       public List<Type<Product>> Components;
       public List<Type<Product>> Prerequisite;
    }

Do you know of a method to do so? Thank you for your thoughts.

Upvotes: 0

Views: 40

Answers (1)

Bas
Bas

Reputation: 27085

Now, your question seems strange to me. Are you sure you don't have a list of Products as components instead of Types? Regardless, here's a way to do it:

class Wheel : Product { }
class Engine : Product { }

class Product {
     List<Type> components;

     public IReadOnlyCollection<Type> Components { get { return components } }

     void AddComponent<T>() where T : Product 
     {
         components.Add(typeof(T));
     }   
 }

 var car = new Product();
 car.AddComponent<Engine>();
 car.AddComponent<Wheel>();

So basically you can register a type known to the caller at compile time and add it to the list of types. This does not allow adding other types since the Components property is read only and does not allow modifying the resulting collection.


Are you sure you don't want a Product's Components to be products as well?

In that case you can use standard polymorphism (specifically, subtype polymorphism):

 Product car = new Product();
 car.Components.Add(new Engine());
 car.Components.Add(new Wheel());
 car.Components.Add(new Wheel());
 car.Components.Add(new Wheel());
 car.Components.Add(new Wheel());

Upvotes: 3

Related Questions