Possible Duplicate:
Can’t operator == be applied to generic types in C#?
I have a “GenericNode”-parent/child structure that I’m trying to make a Find method for.
public class GenericNode<TKey, TName>
{
private GenericNode<TKey, TName> parent;
private readonly TKey key;
private readonly TName name;
private readonly ICollection<GenericNode<TKey, TName>> children;
public GenericNode(TKey key, TName name) {
this.key = key;
this.name = name;
children = new Collection<GenericNode<TKey, TName>>();
}
// AddChild etc...
public GenericNode<TKey, TName> GetChildNodeById(TKey keyToFind)
{
return FindChild(node => node.key == keyToFind); // <--- THIS WON'T COMPILE
}
private GenericNode<TKey, TName> FindChild(Func<GenericNode<TKey, TName>, Boolean> matcher)
{
// Recursive search returning first matching node...
}
}
The above (C# .NET 3.5) doesn’t work because it can’t compare node.key to keyToFind in the GetChildNodeById-method. I’ve been trying different generic constraints etc without luck. How can I specify that the TKey:s are the same type?
I could just create a derived class with a Guid for key and move the GetChildNodeById to that class but I would like a generic solution if possible. Any thoughts?
There are a lot of ways to achieve this:
Make a constraint so that
TKey : IComprabale, then inGetNodeByKeyyou can callCompareon the key.Make a constraint so that
TKey : IEquatable<TKey>, then you can callEqualson the key.Instead of using the equality operator, call
Equalson the key. Note that you risk aNullReferenceExceptionthat way, and that in order to check the key for null you need to add a constraintTKey : class.Call
Object.Equalson the keys. Note that this has a performance hit if your keys are value types, because in the call toObject.Equalsthey will be boxed.Let the user of the tree class provide his comparer. I would recommend adopting the pattern of standard .NET collections. For example look at the different constructors of
Dictionarythat can take a comparer.