- Home /
C# multiple key/value pairs of various types in a single line of code...?
Is there a way to create an object with multiple key/value pairs of differing types in C# like we can with Hashtables in UnityScript in a single line of code?
UnityScript:
var exampleHashtable:Hashtable = {"exampleString":"string", "exampleInt":1, "exampleBoolean:true};
C#
?????? containingObj = {"exampleString":"string", "exampleInt":1, "exampleBoolean:true};
Why would you want to? Type-safety exists for a reason.
I'm porting over a Unity project from UnityScript. It loads external JSON objects that build themselves out by their encapsulated name/value pairs. A parser goes through each of these objects and builds them based on these properties. The properties aren't structured uniformly. For instance, one obj might have {"text":"TITLE TEXT", "font":"Arial", "x":13, "y":22}, while another is {"texture":"/assets/sometexture.png", "width":200, "height"100, "x":50, "y":50}
Answer by Larry-Dietz · Feb 08, 2012 at 01:01 AM
How about using a Dictionary With that you provide a KeyName (string) and and object of any type.
Something like ...
Dictionary<string, object> Parameters = new Dictionary<string, object>();
Parameters.Add("Key1", "A string");
Parameters.Add("Key2", true);
Parameters.Add("Key3", 42);
The above should create a dictionary holding a string, a bool and an int.
They can be referenced like ...
string a = Parameters["Key1"] as string;
bool? b = Parameters["Key2"] as bool?;
int? c = Parameters["Key3"] as int?;
I believe this will accomplish what you are wanting.
Hope it helps,
-Larry
I was pulling my hair out trying to make a dictionary that holds anything. This was very helpful.