Reputation:
I'm having trouble with the following collections initialization:
private Dictionary<string, string> mydictionary = new Dictionary<string, string>()
{
{"key", "value"}
, {"key2", "value2"}
, {"key3", "value3"}
};
I keep getting various compiler errors about the syntax. From what I have googled, this should be perfectly valid C# 3.0 code.
The first error that pops up is:
Error 102 ; expecte
What am I doing wrong?
The line that it keeps telling me it expects the ;
at is right after the closing )
parenthesis.
I am attempting to create this inside of a static class. If I just remove this, than everything compiles fine.
Upvotes: 3
Views: 396
Reputation: 8291
I think you need to get rid of the () (corrected by David Basarab. Thanks David!)
This page shows some good examples: http://www.codeguru.com/csharp/csharp/cs_misc/designtechniques/article.php/c11987
EDIT
Ok, so I finally launched VS2008 and had to give this a try myself.
I pasted the OP's code right into a WinForms project, right in the main "public Form1()" method and hit the Build button and it wouldn't compile.
Delete the "private" keyword and it Compiles just fine.
(I tried using public, internal, etc. and none of those would compile either...)
Upvotes: 0
Reputation: 68400
My conclusion: You're targeting framework 2.0, otherwise it's impossible to get that error.
Are you 101% sure you're using the framework 3.0?
EDIT
1 - On the Project (Solution Explorer), right click on ProjectName and go to Properties.
2 - Check on the Application tab the item "Target Framework"
If says 2.0 change it to 3.0 and do the same for all the projects on the solution.
Upvotes: 3
Reputation: 1700
Look for any potential errors above that line; I copied your code into a new project in Visual Studio and it compiled without any errors. What are you defining this dictionary as a part of?
Upvotes: 0
Reputation: 73301
Are you making it a property/field? You marked it with Private?
Dictionary<string, string> temp = new Dictionary<string, string>()
{
{ "key", "value" },
{ "key1", "value" },
{ "key2", "value2" }
};
This is a local variable Dictionary called temp
private Dictionary<string, string> _fieldDictionary = new Dictionary<string, string>()
{
{ "key", "value" },
{ "key1", "value" },
{ "key2", "value2" }
};
This is a local member.
Both of these compile, is there more code you are leaving out?
I would just start a new class and slowly put in fields, properties, etc. . until you figure out the error. The code you put up is perfectly legal when I am using VS 2008. If you recreate your class slowly it might show you where your error actually is.
Upvotes: 1
Reputation: 1340
What if you just declare the dictionary and then add your key/value pairs.
Dictionary<string, string> temp = new Dictionary<string, string>();
temp.Add("key", "value");
temp.Add("key1", "value1");
temp.Add("key2", "value2");
Upvotes: 0