Home > Software design >  Declare a static variable using an enumerator C# (.NET 6)
Declare a static variable using an enumerator C# (.NET 6)

Time:08-16

Just a simple question, but I cannot find it.

I have this code in 1 file:

namespace Models
{
    public enum MyEnvironment
    {
        Development,
        Testing,
        Acceptance,
        Production
    }
}

And in my program.cs file:

global using Models
static MyEnvironment CurrentEnvironment = MyEnvironment.Development;

With this code I want to set a Environment that is global accessible through my whole code. But I get the error:

the modifier 'static' is not valid for this item

Why can't I use my enumerator in a static variable?

CodePudding user response:

You can't just add a variable on its own, it needs to be inside a class. So your code should be:

global using Models

public static class GlobalVariables // Feel free to choose a better name
{
    public static MyEnvironment CurrentEnvironment = MyEnvironment.Development;
}

Also, note there is no "enumerator" here it is just an "enum" or an "enumeration type".

  • Related