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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With