Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

where t : multiple classes

List<T> Foo<T>(Ilist list) 
where T : ??

is there any way to enforce T to be
one of few classes ?

eventually i want to do a switch on T..

thanks.

like image 662
yoni Avatar asked Jun 29 '10 12:06

yoni


3 Answers

You can require that each class you want to allow into your list implements some interface ISomething and then create a List<ISomething>.

eventually i want to do a switch on T..

Instead of a switch on the type of the object it might be better to have a method in your interface and implement it differently for each class.

like image 144
Mark Byers Avatar answered Sep 21 '22 06:09

Mark Byers


Enforcing a type constraint in this way indicates that those several classes are related with common functionality.

You should implement a common Interface and then restrict the type to that Interface:

public interface IUseful
{
    public void UsefulMethod();
}

List<T> Foo<T>(IList list) where T : IUseful
{
    // You now have access to all common functionality defined in IUseful
}

The added benefit is that now you don't have to switch on T to implement different behaviors. You can have the children of IUseful implement their own behaviors and then call each on their own.

like image 31
Justin Niessner Avatar answered Sep 21 '22 06:09

Justin Niessner


In this case, T could be a common base class or interface that you list objects share. You could have List<IFoo>, and the list could contain classes Foo, Bar, and Baz if they each implement the IFoo interface. Short of using inheritance, you would be stuck with a list of objects.

like image 21
Anthony Pegram Avatar answered Sep 24 '22 06:09

Anthony Pegram