I’m having trouble working through how to add an item to a dictionary that I declare within the dictionary.Add argument.
I have a struct called option with 2 strings.
I have a dictionary within a class called Contains.
I want to accomplish
option Change = new option("change","change");
Contains.Add(contains.Count + 1, Change);
on the same line. Is this possible?
I tried
Contains.Add(contains.Count + 1, option Change = new option("change","change"));
and it did not work.
I’m sure the answer is simple, I just haven’t been able to figure it out using google or this site after 30 minutes of searching. Sorry!
you can do either
or
the first code block creates a new instance of
optionon the spot and adds it to the dictionary. the second code block creates a new variable of typeoption(a reference to an instance ofoption) and adds it to the dictionary. you cannot declare a new variable within the call to the Contains.Add method, that is illegal.PS: the C# language specification documents scope, local variable declaration, and statements. in case you want to read up on how to declare variables in C# these will be the most relevant topics to you (but probably a bit hard to grasp from the formal C# language specification, so I’d recommend picking up a good book on how to get started with C# and look for some tutorials like those on MSDN).