Custom array index. [c#]

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • Markus
    Recognized Expert Expert
    • Jun 2007
    • 6092

    #1

    Custom array index. [c#]

    In PHP we can do this to use a custom array index:
    Code:
    $array = array("my_index" => "my_index's value");
    and access it by:
    Code:
    echo $array['my_index'];
    I've had a look around, but I can't seem to find a way of doing this in C#.

    Is it possible to do that?
  • tlhintoq
    Recognized Expert Specialist
    • Mar 2008
    • 3532

    #2
    'Custom' index?

    I'm not sure what you mean by a 'custom' index. Is this somehow different than a regular array index?

    Code:
                int myIndex = 2;
                string[] myStringArray = { "Alpha", "Bravo", "Charlie" };
                Console.WriteLine(myStringArray[myIndex]); // Should produce "Charlie" sine arrays are zero indexed

    Comment

    • mldisibio
      Recognized Expert New Member
      • Sep 2008
      • 191

      #3
      I think these are called "associativ e arrays" where the index is named. No, you cannot do that with CLR arrays (out of the box), but you can achieve close to the same with a Hashtable:
      Code:
      Hashtable array = new Hashtable();
      array.Add("my_index", "my_index's value");
      Console.WriteLine(array["my_index"]);
      Also, a generic Dictionary<stri ng, string> and several other collection types will do it.
      Another option is to write your own Collection<T> and add a custom Indexer which accepts a string index value instead of the default int.

      Comment

      • Plater
        Recognized Expert Expert
        • Apr 2007
        • 7872

        #4
        Yeah, the Dictionary object is your ticket.
        If you just want a string index, the NameValueCollec tion might be more usefull.
        Its roughly just Dictionary<stri ng,string>
        Dictionary<stri ng,object> is roughly what is used for the Session(and Application) object collection in web applications

        Comment

        • Markus
          Recognized Expert Expert
          • Jun 2007
          • 6092

          #5
          Thanks for that, guys.

          Comment

          Working...