Search code examples
c#visual-studiodictionaryvisual-studio-2019monogame

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


I am currently working on a project in Visual Studio 2019 Community and after a little while of programming it just stopped accepting new variables in a way.

I was trying to create a dictionary to bind some keys to certain actions and when I tried to add to the dictionary using keyBindings.add(foo, bar) Visual Studio and the compiler stopped recognizing the variable as even existing. Now, in any file or class, when I try to create a variable and set it to something or use it, it just throws Invalid token '=' in class, record, struct, or interface member declaration for the = sign and states that variable does not exist in the current context.

i.e.

int x;
x = 10;

It will throw error CS1519 on the second line.

Here is all of my code, so far, relating to the dictionary itself.

class KeyboardHandler
    {
        Dictionary<_Keys, Actions> keyBindings = new Dictionary<_Keys, Actions> ();


        public bool isKeyPressed(_Keys key)
        {
            if (Keyboard.GetState().IsKeyDown((Keys)key))
            {
                return true;
            }

            return false;
        }
    }

_Keys and Actions reference enums outside of the class.


Solution

  • Directly inside a class, you can only define variables, properties and methods. For example, this code is fine:

    class Example
    {
       private int x;
       public string y { get; set; }
       public void MethodA() { }
       public void MethodB() { }   
    }
    

    However, this is not allowed

    class Example2
    {
        Console.WriteLine("abc");
    }
    

    Because it is not the definition of a variable, property or a method. You have to move the statement above inside a method:

    class Example3
    {
        public void Method()
        {
             Console.WriteLine("abc");
        }
    }
    

    In your case, if you want to fill the dictionary, you can do it in the constructor. The constructor will be called when a new instance of your class is created. Hence you can be sure that your dictionary is filled when you call any methods of your instance:

    class KeyboardHandler
    {
        Dictionary<_Keys, Actions> keyBindings = new Dictionary<_Keys, Actions> ();
    
        public KeyBoadHandler()
        {
             keyBindings.Add(foo, bar);
        }
    
        public bool isKeyPressed(_Keys key)
        {
            if (Keyboard.GetState().IsKeyDown((Keys)key))
            {
                return true;
            }
            return false;
        }
    }