Like almost all uses of generics, the benefits come to the consumer. A type restriction gives you the same advantages that you get by strictly typing your parameter (or you can do other things, for example, make sure that there is an open constructor without parameters or provide it with either a value or a reference type), while preserving all the subtleties generics for the consumer of your class or function.
Using generics also, for example, allows you to get the actual type that was specified if it has any particular value.
This example is a little contrived, but look at this:
public class BaseClass { public void FunctionYouNeed(); } public class Derived : BaseClass { public void OtherFunction(); } public class MyGenericClass<T> where T: BaseClass { public MyGenericClass(T wrappedValue) { WrappedValue = wrappedValue; } public T WrappedValue { get; set; } public void Foo() { WrappedValue.FunctionYouNeed(); } } ... var MyGenericClass bar = new MyGenericClass<Derived>(new Derived()); bar.Foo(); bar.WrappedValue.OtherFunction();
source share