In "C# 6.0 in a Nutshell" there is an example of naked type constarint usage:
class Stack<T>
{
Stack<U> FilteredStack<U>() where U : T {...}
}
Honestly, I don't understand why I should use this constraint here. If I'll remove it and change U to T, result will be the same. So what's the point?
Thank you.
The point is that
U
can be any type that is a subclass ofT
, and theStack
you get back is a stack of that type, not ofT
. Therefore, items added to it must be of typeU
, and items you get back out of it are guaranteed to beU
if they're not null. All the familiar joys and sorrows of compile-time type checking.The items in the
Stack<T>
could be of typeT
, or any subclass ofT
. The name of that method suggests that it's returning a stack that contains only the items in the parent stack that are actually of some particular subclass. Once you're guaranteeing that all the items in the new stack are of the more specialized type, it's far more useful if that's the type of the new stack as well.Here's a wildly contrived example (clearly, this "stack" class doesn't actually do anything a stack does, but for our example it doesn't need to):