I have the following code in C#:
1)
public class MyBinaryTree<TItem> where TItem : IComparable<TItem>
{ ... };
2)
public class MyBinaryTree<TItem> : IComparable<TItem>
{ ... };
I found this sample at this site, but it is not entirely the way I want.
The first example/code tells us that item (TItem) implements the interface IComparable.
The second example/code tells us that our whole class (MyBinaryTree) implements the interface IComparable.
I do not understand it very well.
The first example I’ve never used and the second I use often (this is a classic example of the interface). Some advice – supplements?
How does it apply in practice?
The difference is that the second example is interface inheritance. The second is constraints on what the generic type can be.
Interface inheritance means that the class that inherits that interface MUST provide implementations (unless it is abstract) of the methods contained within the interface. So, this essentially imposes constraints on the class and how it is built
Constraints on the other hand, impose constraints on the generic type that is used within the class. This allows the implementation to be able to make certain assumptions as to what TItem will be allowed to do within the class.
Examples:
Inheritance
Type Constraints
So, you will notice that inheritance forces the class to implement a method. Whereas type constraints do not force anything on the class implementation. Instead, type constraints force that
Tmust implementIComparable. So, that way you can rely onThaving access to theCompareTomethod