I have a class A from which B and C inherit.
I also have lists of B and C like so: List<B> listB
and List<C> listC
.
I want to add elements to these lists but only after I do some logic. I have made a method that takes a list of any type and a related item to add.
public void AddItemToList<T>(List<T> item_list, T new_item)
{
//do logic with properties of A...
}
I need to be able to use this method with both lists, like so:
AddItemToList<B>(listB, new B());
AddItemToList<C>(listC, new C());
However, since the type is generic, I cannot do the logic I want inside the method using A's properties.
If I use type A in the method, then I cannot pass the lists or items without casting them first.
Is there a way to set the type so I can pass matching parameters while still being able to do logic inside the method?
You can put a constrain on T, using
where
in method declarationSee where (generic type constraint)