Reputation: 13843
In C#, i have an interface, and there are some class will implement this interface. i have a generic utility class, which i want to limit so that the utility class can only be declared using types implementing that interface, as show below, how can i do it??
public interface IMyInterface
{}
public class A : IMyInterface {} // can pass into UtilityClass
public interface B : IMyInterface{}
public class C : B {} // can pass into UtilityClass
public class D {} // can Not pass into UtilityClass
public class UtilityClass<T is IMyInterface>
{
// some utility function
}
Thanks.
Upvotes: 0
Views: 98
Reputation: 424
public class UtilityClass<T> where T: IMyInterface
{
// some utility function
}
They are called constraints, you can read more here http://msdn.microsoft.com/en-us/library/d5x73970.aspx
Upvotes: 1
Reputation: 115763
You can add restrictions to generic classes like so:
public class UtilityClass<T> where T : IMyInterface
{
// some utility function
}
Upvotes: 0
Reputation: 7347
use the where clause:
public interface IMyInterface
{}
public class UtilityClass<T> where T : IMyInterface
{
// some utility function
}
Upvotes: 0
Reputation: 185593
You're looking for a generic constraint. These are expressed in C# by using the where
keyword after the class name.
public class UtilityClass<T> where T:IMyInterface
{
}
Upvotes: 6