#1,138 – Type Parameters in Generic Methods Can Be Constrained
July 15, 2014 2 Comments
You can constrain the type parameters in a generic class in a number of different ways. You can also constrain type parameters in generic methods, using the same types of constraints.
In the example below, we define a generic method Bury<T> in the Dog class. We constrain the type parameter, indicating that it should implement the IBuryable interface.
public class Dog { public string Name { get; set; } public Dog(string name) { Name = name; } // Generic method public void Bury<T>(T thing) where T: IBuryable { Console.WriteLine("{0} is burying: {1}", Name, thing); } }
We can pass the Bury method any object that implements IBuryable.
Dog d = new Dog("Bowser"); d.Bury(new Bone());
If we try passing an object that does not implement IBuryable, we’ll get a compile-time error, indicating that the compiler can’t convert to IBuryable.
What is the difference between this constrained generic and this:
public void Bury(IBuryable thing)
{
Console.WriteLine(“{0} is burying: {1}”, Name, thing);
}
It depends on what you want to do within the method (or generic type), i.e. whether you want to treat the parameter as an object of type T, or just call methods in the IXxxx interface on it. See http://stackoverflow.com/questions/7224675/practical-advantage-of-generics-vs-interfaces-in-c-sharp for some good discussion on this.