using a structure within an array

I want to create a read only array using a structure as the elements, then perform a binary search on an element of the structure within the array (or arraylist ). Your help would be much appreciated.

Answer this question

using a structure within an array

  • Edwardo

    You can make an array of anything you want, structures included.  Making it read-only is simple enough as well, at least in C#.  As for the binary search, all you have to do for that one is examine the structure for the value you're looking for during the search.

    Here's an example of a read-only array of structs:
    public struct Structure
    {
       // These should be encapsulated as properties in actual code, but for the sake of brevity 
       // I won't do that here
       public string Prop1;
       public string Prop2;
    }

    public class Bob
    {
       public readonly Structure[] stuff;   // You can initialize it either here or in the constructor
       
       public Bob()
       {
          Structure thing1 = new Structure();
          thing1.Prop1 = "Bob";
          thing1.Prop2 = "Jim";

          // Declare and instantiate another Structure -- thing2

          stuff = new Structure[]{ thing1, thing2 };
       }
    }

    Then when you search, as you go through each item in the array you can check its properties.

    Hope this helps.

    -Ari

  • using a structure within an array