13

Can you do

array['Name'];

In C#

Rather than:

array[0];

I know you can do that in PHP but is there an equivelent for C#, although im thinking highley unlikely :(

3 Answers 3

20

it's called a Dictionary in C#. Using generics you can actually index by any type. Like so:

Dictionary<Person, string> dictionary = new Dictionary<Person, string>();
Person myPerson = new Person(); 
dictionary[myPerson] = "Some String";
...
string someString = dictionary[myPerson];
Console.WriteLine(someString);

This obviously prints, "Some String" to the console.

This is an example of the flexibility of the dictionary. You can do it with a string as an index too, like you asked for.

Sign up to request clarification or add additional context in comments.

2 Comments

Yeap, have a look at System.Collections msdn.microsoft.com/en-us/library/system.collections.aspx
@xandercoded, you probably want System.Collections.Generic. System.Collections is the non-generic form from .net 1.
8

Arrays don't work like that in C#, but you can add an indexer property to any class:

class MyClass
{
    public string this[string key]
    {
        get { return GetValue(key); }
        set { SetValue(key, value); }
    }
}

Then you can write the type of statements you ask against this:

MyClass c = new MyClass();
c["Name"] = "Bob";

This is how string-based indexed access to Dictionary<TKey, TValue>, NameValueCollection and similar classes are implemented. You can implement multiple indexers as well, for example, one for the index and one for the name, you just add another property as above with a different parameter type.

Several built-in framework classes already have these indexers, including:

  • SortedList<TKey, TValue>
  • Dictionary<TKey, TValue>
  • SortedDictionary<TKey, TValue>
  • NameValueCollection
  • Lookup<TKey, TValue> (in System.Linq)

...and more. These are all designed for slightly different purposes, so you'll want to read up on each and see which one's appropriate for your requirement.

Comments

4
Dictionary<string, whatyouwanttostorehere> myDic =
                            new Dictionary<string, whatyouwanttostorehere>();
myDic.Add("Name", instanceOfWhatIWantToStore);   
myDic["Name"];

1 Comment

thats what I meant sorry, it didnt show up entirely first time.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.