Search code examples
c#arraysindexof

How to get an element within an array


I have a fixed list of strings, which I've put inside an array. I'm using IndexOf() in order to get an element out of such an array but that seems not to work:

using System.Runtime;

  ...
  static string[] Alarm_Names = new string[3] {"A1",  "A2",  "A3"}
  static bool[]   arr_Alarms  = new bool[3]   {false, false, false};

  internal static void HandleAlarm(..., string code, ...)
  {
    if (arr_Alarms[IndexOf(Alarm_Names, code)]) return;       // does not compile
    if (arr_Alarms[Array.IndexOf(Alarm_Names, code)]) return; // does not compile

The function/static method IndexOf() seems not to exist, although this page mentions otherwise.
Most probably this is due to the fact that I'm programming in C#, .Net Framework 4.6.1, which is not recent enough for the .Net 6 version of the mentioned page.

As you can see, I have a list of constant strings, I would like to make a list of booleans for each of those strings and in case a string is entered as a function parameter, I would like to check the boolean list for checking the value, and the function IndexOf() was the perfect tool for that.
Are there other simple ways? (Or is my analysis wrong and can I do something very simple in order to make this work, without modifying the version of my target .Net framework?)


Solution

  • IndexOf is a static method defined on the Array class. Since your code is not part of that class, you need to prefix it with the class name, as you have done in your second attempt:

    Array.IndexOf(Alarm_Names, code)
    

    Other than that, the only compiler error in your code is the missing semicolon from the Alarm_Names field.

    Having fixed that, your code will compile (barring other errors in the parts of the code which aren't shown).

    using System; // needed for accessing "Array"
    
    class YourClass
    {
        static string[] Alarm_Names = new string[3] {"A1",  "A2",  "A3"};
        static bool[]   arr_Alarms  = new bool[3]   {false, false, false};
    
        internal static void HandleAlarm(..., string code, ...)
        {
          if (arr_Alarms[Array.IndexOf(Alarm_Names, code)]) return;
    

    If it still won't compile, you'll need to list the actual compiler errors you're getting.


    NB: If you're using C# 6 or later, you could use the using static feature to make all static members of the Array class available to call without the Array. prefix:

    using static System.Array;
    
    class YourClass
    {
        static string[] Alarm_Names = new string[3] {"A1",  "A2",  "A3"};
        static bool[]   arr_Alarms  = new bool[3]   {false, false, false};
    
        internal static void HandleAlarm(..., string code, ...)
        {
          if (arr_Alarms[IndexOf(Alarm_Names, code)]) return;
    

    static modifier | using directive | C# Reference