Reputation: 41
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!
Upvotes: 1
Views: 306
Reputation: 3678
you can do either
Contains.Add(contains.Count + 1, new option("change", "change"));
or
option Change = new option("change", "change");
Contains.Add(contains.Count + 1, Change);
the first code block creates a new instance of option
on the spot and adds it to the dictionary. the second code block creates a new variable of type option
(a reference to an instance of option
) 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).
Upvotes: 4
Reputation: 12735
You can try the following :
Contains.Add(contains.Count + 1, new option("change", "change"));
Upvotes: 2
Reputation: 10376
Just
Contains.Add(contains.Count + 1, new option("change","change"));
Upvotes: 4