jeremychan
jeremychan

Reputation: 4459

problem with dictionary class

I saw this article on msdn with the example http://msdn.microsoft.com/en-us/library/xfhwa508.aspx

So i decided to give it a shot and try this out in my wpf application:

Dictionary<string, string> Dictionarycheck =
    new Dictionary<string, string>();

Dictionarycheck.Add("demo1");

Why this won't work? I get the error: Invalid token '(' in class, struct, or interface member declaration

Upvotes: 0

Views: 605

Answers (3)

Morten
Morten

Reputation: 3844

You are probably writing the code outside of a method (like I just did to test it). Further, Dictionary.Add has two arguments.

Upvotes: 1

Jan Johansen
Jan Johansen

Reputation: 2059

Dictionary(TKey, TValue)

So its Dictionarycheck.Add("Key", "Value");

Upvotes: 1

Jon Skeet
Jon Skeet

Reputation: 1500065

Two problems:

  • You can't just add a key to a dictionary. You have to add a key/value pair
  • You can't include statements directly in a class declaration - they have to be in constructors/methods/properties/etc. This is the direct cause of your problem, given your error message.

In other words, you've probably got something like this:

public class Test
{
    Dictionary<string, string> Dictionarycheck =
        new Dictionary<string, string>();

    Dictionarycheck.Add("demo1");
}

when it should be something like this:

public class Test
{
    public void DemoMethod()
    {
        Dictionary<string, string> dictionaryCheck =
            new Dictionary<string, string>();

        dictionaryCheck.Add("demo1", "value1");
    }
}

(I've adjusted the name of the variable for convention, too.)

Upvotes: 5

Related Questions