Search code examples
c#access-modifiersclass-visibility

Can't pass protected enum as parameter for static method


I've been updating the company's software and stumbled upon this problem. There's this enum that's protected and I want to pass a value from that enum as a parameter for a static method, but I can't cause I have no access to it even though both the method and the enum are in the same class.

Example:

Class SomeClass
{    
    protected enum Car
    {
        Id
    };

    public static void AMethod(Car enumValue)
    {
        MessageBox.Show("This is an enum:" + enumValue.ToString());
    }  
}

I can't use this Car enumValue as parameter for AMethod cause I have no access to it. Why can't I do this? I mean they're in the same class. Am I missing something?


Solution

  • The issue is not that your SomeClass can't see the enum. The problem is your enum has a protected access modifier, and you're trying to use it in a public method (i.e. accessible outside your class). You can't expose a protected type through a public member because methods in other classes can't see the enum when they're trying to call AMMethod().

    Depending on how you intend to use this class, you need to change either one or the other so the access modifiers match:

    public enum Car
    {
        Id
    };
    
    public static void AMethod(Car enumValue)
    {
        MessageBox.Show("This is an enum:" + enumValue.ToString());
    }  
    

    or:

    protected enum Car
    {
        Id
    };
    
    protected static void AMethod(Car enumValue)
    {
        MessageBox.Show("This is an enum:" + enumValue.ToString());
    }  
    

    The latter one will just prevent the compiler error, but it may be the case that you want AMethod to be public, so you should choose the former.