How to use dictionary in c# and Unity?

Hello guys!

Is it correct to use the dictionary in the following way:

Dictionary <MyOtherClass, string> diction= new Dictionary<MyOtherClass, string>();

diction.Add(new MyOtherClass, "some text");
diction.Add(null, "some chars");


void OnEnable( ){

   MyOtherClass _class = diction["some text"];

  Debug.Log(typeof(_class).ToString() ); 
}

Couple of Questions:

  1. Will the last line write the type of the class sitting along with “some text string”?

  2. Does dictionary preserve items in the order I added them?

  3. If so, can I obtain a KeyValuePair from a 2nd pair, similar to list index?

  4. Can both key and value be of any type as stated when the dictionary is initialized?

  5. What happens when my values are duplicates in the dictionary? That is, some of the keys are the same for example

  6. Thank you! :slight_smile:

When you add to the dictionary, the first value is the key, the second is the value. So In your case, above you will not be able to add null because that is not a valid key. You CAN use null for a value. I have a feeling that you are doing it backwards and want the String to be the key, and the object to be the value.

This line

MyOtherClass _class = diction["some text"];

Will tell you the key doesn’t exist because above you added it as the value for a key that is an object

1.) No it will fail before you get here
2.) No
3.) I don’t know what this means but since it piggies off 2, guess it doesn’t matter
4.) I believe so, but it’d probably be a pretty rare situation where the key would be anything other than a string
5.) You cannot add duplicate keys, only values.
6.) Sure!