IMO the best way to check if an array contains a given value is to use System.Collections.Generic.IList<T>.Contains(T item)
method the following way:
((IList<string>)stringArray).Contains(value)
Complete code sample:
string[] stringArray = { "text1", "text2", "text3", "text4" };
string value = "text3";
if (((IList<string>)stringArray).Contains(value)) Console.WriteLine("The array contains "+value);
else Console.WriteLine("The given string was not found in array.");
T[]
arrays privately implement a few methods of List<T>
, such as Count and Contains. Because it's an explicit (private) implementation, you won't be able to use these methods without casting the array first. This doesn't only work for strings - you can use this trick to check if an array of any type contains any element, as long as the element's class implements IComparable.
Keep in mind not all IList<T>
methods work this way. Trying to use IList<T>
's Add method on an array will fail.