I want to write a generic function that has a constraint on the type. Specifically I want something like this:
bool IsInList<T>(T value, params T[] args)
{
bool found = false;
foreach(var arg in args)
{
if(arg == value)
{
found = true;
break;
}
}
return found;
}
The point being that you can check if an item is in a parameter list viz:
if(IsInList("Eggs", "Cheese", "Eggs", "Ham"))
However, the compiler croaks on the equality line. So I want to put in a constraint on the type that it implements IEquatable. However, constraints only seem to work at the class level. Is this correct, or is there some way to specify this generically?
Generic constraints work on generic methods as well:
bool IsInList<T>(T value, params T[] args) where T : IEquatable<T>
BUT, IEquatable<T>
doesn't define operator ==
, only Equals(T)
.
So, you should use Equals()
and you don't even need the constraint for that: Equals(object)
is member of object
.
Also don't forget that Equals
won't work if the object is null
.