I’ve read an excellent article on MSDN regarding Generics in C#.
The question that popped in my head was – why should i be using generic constraints?
For example, if I use code like this:
public class MyClass<T> where T : ISomething
{
}
can’t I switch ALL references of T in this class with ISomething?
What’s the benefit of using this approach?
You ask, “can’t I switch ALL references of
Tin this class withISomething?” So I think you mean to compare:With:
In the second example,
MyPropertyis only guaranteed to be an instance ofISomething. In the first example,MyPropertyis whateverTis, even if that is a specific subtype ofISomething. Consider a concrete implementation ofISomething:Now, if we use the first, generic, example, we could have:
On the other hand, if we used the second example, we wouldn’t be able to access
MyOtherPropertysince it’s only known to be anISomething:On a different note, the reason these type constraints are useful is that you can refer to
MyProperty(typeT) and access members ofISomething. In other words, ifISomethingwere declared like:Then you could access
MyProperty.SomeProperty. If you omitted thewhere T : ISomethingthen you wouldn’t be able to accessSomePropertysinceTwould only be known to be of typeobject.