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.
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.
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.
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.
As far as I know, this is not possible. I would recommend deriving your limited set of classes from a common base class or interface.
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.
What is it do you want? After the colon, you may enumerate the types to which you constraint T
to.
For multiple classes, perhaps implementing one generic interface and setting your constraint to it might do the trick.
Please look at this link for further details: Constraints on Type Parameters (C# Programming Guide)