Reputation: 3364
I would like to create a generic class Node as follow:
public class Node<T>
{
public Node<T> Next;
public Node<T> Previous;
T Content;
public Node<T>()
{
}
}
In my main (or from other class) I would like to compare items.. something like the following: (I use pseudo code to illustrate my idea, the code may or may not really work). Basically I would like to find if the item I have is in the list.
main()
{
List<Node<T>> n = new List<Node<T>>()
bool found = false;
T v = new T();
foreach (Node<T> i in n)
{
if i.Content== v
{
found = true;
}
}
}
I understand in order to compare 2 instances of a class, I have to derive my class from IEquitable, but I would like to know if T belongs to predefined classes that we have been using all the times like int, double, string ... I do not want to redefine those classes but would expect the comparison to work and use the default comparator. How do I write the above so that c# would accept it and throw out a syntax error?
if i.Content== v
{
found = true;
}
I have tried
if (T)i.Content == (T)v
{
...
}
The compiler does not seem to like it. Actually, I did the following:
Node<T> r = n.Where(x=> (T)x.Content==(T)v).FirstOrDefault()
The error I got was: Operator == could not applied to operands of type 'T' and 'T' Please advise. Thanks!
Upvotes: 1
Views: 67
Reputation: 24661
You could change your Node<T>
declaration to the following:
public class Node<T> where T : IEquatable<T>
Then you would be able to use:
if (i.Content.Equals(v))
// ...
Upvotes: 1
Reputation: 144126
You can use IEqualityComparer<T>
:
var comp = EqualityComparer<T>.Default;
if (comp.Equals(i.Content, v)) {
...
}
Upvotes: 4
Reputation: 63722
There is no way to specify operators in generic constraints (with the exception of the parameter-less constructor, if you consider it an operator).
If you need some way of comparison, you need to use a method. Either use Equals
, or add some interface like IComparable<T>
as a generic constraint.
Upvotes: 0