FenryrMKIII
FenryrMKIII

Reputation: 1198

Invalid token '(' in class, record, struct or interface member declaration

I am learning Blazor and C# (new to both) and am playing with a pet project of mine.

For that project, I have written a Project.cs file located in the Data directory of the structure that was created following this tutorial.

At some point, I need a dictionnary data structure that I try to create like this within a class :

namespace MyApp.Data;

public class Project
{
    public Project()
    {
    }

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

    // Add some elements to the dictionary. There are no
    // duplicate keys, but some of the values are duplicates.
    openWith.Add("txt", "notepad.exe");
    openWith.Add("bmp", "paint.exe");
    openWith.Add("dib", "paint.exe");
    openWith.Add("rtf", "wordpad.exe");
}

But I receive the error Invalid token '(' in class, record, struct, or interface member declaration whereas I took the lines from Microsoft's documentation directly

What am I doing wrong ?

Upvotes: 1

Views: 18292

Answers (1)

Serge
Serge

Reputation: 43969

you cant' run any code inside of the class. You can move your code inside of the constructor or inside of a special method or you can init property directly using {}.

public class Project
{
        Dictionary<string, string> openWith =
    new Dictionary<string, string>();

   public Project()
    {

    openWith.Add("txt", "notepad.exe");
    openWith.Add("bmp", "paint.exe");
    openWith.Add("dib", "paint.exe");
    openWith.Add("rtf", "wordpad.exe");

    }
}

    

Upvotes: 8

Related Questions