Reputation: 32400
I've written a class that looks like this:
public class MyClass<T>
{
public void doSomething()
{
T.somethingSpecial;
}
}
This code doesn't compile because the compiler has no idea what T is. I would like to constrain T so that it must inherit a certain class that defines somethingSpecial
. Bonus points if you can tell me how to do the same thing by contraining T so that it must implement a certain interface.
Upvotes: 3
Views: 1430
Reputation: 62157
Read the documentation. Generic Constraint.
class MyClass<T> where T : someinterfaceorbaseclassthatTmustinherit
Upvotes: 1
Reputation: 8623
public interface ISomeInterface
{
void DoSomething();
}
public class MyClass<T> where T : ISomeInterface
{
public void doSomething()
{
T.DoSomething();
}
}
The where
keyword allows you to specify constraints on the given generic type. You could swap out the interface for a class.
Upvotes: 1
Reputation: 245479
What you want is a generic constraint:
public class MyClass<T> where T : SomeParentClass
Upvotes: 4
Reputation: 41767
You need a Generic Constraint:
public class MyClass<T> where T : ISomeInterface
{
public void doSomething()
{
instanceOfT.somethingSpecial();
}
}
Upvotes: 1
Reputation: 27974
Use the following type parameter constraint in the class declaration:
public class MyClass<T> where T : MyBaseClass
You can read more about type parameter contraints for example here at MSDN.
Upvotes: 4
Reputation: 50235
public class MyClass<T> where T: IAmSomethingSpecial
It's called Constraints on Type Parameters.
Upvotes: 15