Click here to Skip to main content
15,867,488 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hello everyone,

So far I couldn't understand how, for the following implementation, this works... BIt is not something that I am using, it is from a book I am reading.

class BinaryTreeNode<TNode> : IComparable<TNode> where TNode : IComparable<TNode> 
{ 
    public BinaryTreeNode(TNode value) { Value = value; } 
    public BinaryTreeNode<TNode> Left { get; set; } 
    public BinaryTreeNode<TNode> Right { get; set; } 
    public TNode Value { get; private set; } 

     public int CompareTo(TNode other) 
     { 
         return Value.CompareTo(other); 
     } 
}


Why/How does "Value" knows what to do when you call CompareTo() and "BinaryTreeNode<tnode>" must have it defined?
I tested with primitive type and it works fine, but with the Object Class or some of my classes, it shows "this argument type is not within bounds". Why does it happen? How to fix it?

Regards,
Posted

1 solution

The generic definition has a where clause that tells the compiler that the actual TNode type must implement IComparable<TNode>. So, the compiler knows that the instanciated generic type has a CompareTo(...) method.
You can only instanciate BinaryTreeNode<...> with a type that fulfills that where constraint. E.g. string fulfills that constraint. See http://msdn.microsoft.com/en-us/library/system.string.aspx[^]:
C#
[SerializableAttribute]
[ComVisibleAttribute(true)]
public sealed class String : IComparable, 
	ICloneable, IConvertible, IComparable<string>, IEnumerable<char>, 
	IEnumerable, IEquatable<string>

Cheers
Andi
 
Share this answer
 
v2
Comments
Paulo Augusto Kunzel 10-Oct-13 16:46pm    
Hello Andreas,

Let me see if I understood, so the WHERE clause is saying that the TNode is an object that implements the IComparable? What if it doesn't? could you give me some extra examples?

thx
Zoltán Zörgő 10-Oct-13 17:00pm    
What if it doesn't? You will get a compile time error.
Andreas Gieriet 10-Oct-13 17:02pm    
If you have a compiler at hand, try it out!
E.g.
public class B<T> where T: IComparable<T> {}
public class C {}
public class D { B<C> _var; }
Sergey Alexandrovich Kryukov 10-Oct-13 17:34pm    
Answered. A 5.
—SA
Andreas Gieriet 10-Oct-13 17:49pm    
Hello Sergey,
Thanks for your 5!
Cheers
Andi

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900