CKTIS / C#
Array.IndexOf: Find an allowed status
Use the static `Array.IndexOf` method to find the first occurrence of a status in an array and check whether that status is allowed.
Version: C# 12 and .NET 8; later runtimes may add compatible features
Syntax
public static int IndexOf<T>(T[] array, T value);
// With string[] AllowedStatuses and string s2:
int index = Array.IndexOf(AllowedStatuses,s2);
bool isAllowed = index >= 0;In C# 12 on .NET 8, Array.IndexOf(AllowedStatuses,s2) searches the entire one-dimensional string[] named AllowedStatuses for the string value s2. This is a static method on System.Array. The compiler selects the two-argument generic overload IndexOf<T>(T[], T) and infers T as string. It does not select the nongeneric overload IndexOf(Array, object).
The method returns an int: the zero-based index of the first match, or -1 if nothing matches. Use index >= 0 to check whether the status is allowed, including when it appears at the first position. Do not use -1 as an array index. If the array itself is null, the method throws ArgumentNullException instead of returning -1.
The method uses default equality for the element type. For string, that means an ordinal, culture-insensitive, case-sensitive comparison. This overload does not accept a custom comparer.
Do not confuse this method with a function you write called IndexOf, or with System.Collections.Generic.List<T>.IndexOf, which you call on a list instance, as in list.IndexOf(s2).
Examples
using System;
string[] AllowedStatuses = { "open", "closed", "open" };
string s2 = "open";
int index = Array.IndexOf(AllowedStatuses,s2);
Console.WriteLine(index);
Console.WriteLine(index >= 0);
s2 = "Open";
index = Array.IndexOf(AllowedStatuses,s2);
Console.WriteLine(index);
Console.WriteLine(index >= 0);Result
0 True -1 False
`"open"` first matches at index `0`, so the condition gives `True`. `"Open"` has no match, so the result is `-1` and the condition gives `False`.
Related lessons
- C# · Lesson 32 · Basic · Version: 3