generic method that tests if array contains a value

  • Thread starter Thread starter Steve Richter
  • Start date Start date
S

Steve Richter

Is it possible to write a generic method which returns true or false,
depending on if the array contains a value?

Is there already a framework method that provides this functionality?

the following code does not compile. Error is: Operator == cannot be
applied to operands of type T and T.

public static bool Contains<T>(T[] InValues, T InPattern)
{
bool doesContain = false;
foreach (T vlu in InValues)
{
if (vlu == InPattern)
{
doesContain = true;
break;
}
}
return doesContain;
}
 
Steve Richter said:
the following code does not compile. Error is: Operator == cannot be
applied to operands of type T and T.

You can get it to compile if you use Equals instead of == :

if (vlu.Equals(InPattern))
{
doesContain = true;
break;
}

If the class <T> does an adequate override of Object.Equals, then you
will get a meaningful behaviour. Otherwise, Equals defaults to calling
ReferenceEquals, which will consider the two elements you are comparing to
be equal if they contain the same reference, and will consider that they are
different if the reference is different, regardless of wether the contents
are equal or not. This may or may not be adequate for your needs, depending
on what <T> is and what you want to do with it.
 
Well, you could use Array.IndexOf<T>(array, instance) >= 0...

However, ICollection<T> has a Contains(T) method, and T[] :
ICollection<T>, hence (and more re-usable, if trivial):

static void Main() {
int[] values = { 1, 2, 3, 4, 5 };
Console.WriteLine(Contains(values, 3));
Console.WriteLine(Contains(values, 6));
}
static bool Contains<T>(ICollection<T> data, T value) {
if (data == null) throw new ArgumentNullException("data");
return data.Contains(value);
}

Marc
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Back
Top