Search code examples
c#structmembernon-static

c# accessing struct members within class' methods


i'm trying to write a simple game. I want to design a "movement controller" object, that would handle move instructions from the engine. I would also like for this object to expose a method, that would check its state and return true/false depending if it's ready to move or not. The state will be saved as group of boolean variables. Since there is a lot of them, I decided to group them together in a new struct called "flags". This is how it looks like more or less:

public class movContr
{
    int movId;
    public struct flags
    {
        bool isMoving;
        bool isLocked;
        bool isReady;
        (...)
    }

    public bool CheckReadiness()
    {
        if(flags.isReady==true) return true;
        return false;
    }
}

Now the problem is this won't compile, error being:

error CS0120: An object reference is required to access non-static member

offending line being:

if(flags.isReady==true) return true;

So I guess C# doesn't treat structs like memory blobs that just contains variables in orders, but like some "special" cousin of a class.

Here are my questions:

how should I handle accessing struct class members in its methods? How can I refer in class methods to members of its future instances? I tried this instead:

if(this.flags.isReady==true) return true;

but i get the same error.

Alternatively, if encapsulating my flag variables using 'struct' is not a proper way to do so, what is?

I tried to find an answer myself but since all the keywords I could come up with are very generic, so are the results. Most deal with static members, which are not a solution here since I need multiple, independent instances of movContr class.


Solution

  • You have created a declaration of struct called flags. But it is only declartion, not a concrete value. So, the snippet

    if(flags.isReady==true) return true;
    

    tries to access static member (https://msdn.microsoft.com/en-us/library/98f28cdx.aspx).

    You need to declare a variable of that type in order to use it:

    private flags myFlag;
    
    public bool CheckReadiness()
    {
         if(myFlag.isReady==true) return true;
          return false;
    }
    

    Maybe your confusion comes from C++, where "inline, anonymous" struct is allowed:

    struct {
        int some_var
    } flags;
    
    flags.some_var = 1;
    

    It is not available in C#