Is it possible to limit instances of public inner enum or class to its parent class in C#?

80 views Asked by At

I would like to define an enum inside of a class. The class will have a public property of the enum type. I would like classes outside this class to be able to reference this class' enum property, but I don't want other classes to be able to create their own instances of this enum. Is this even possible? Consider this example:

public class MyClassWithEnum
{
    public Season MySeason { get; set; }
    public enum Season { Winter, Spring, Summer, Fall }
}

public class OutsideClass
{
    public void OutsideClassMethod()
    {
        MyClassWithEnum enumClass = new MyClassWithEnum();

        enumClass.MySeason = MyClassWithEnum.Season.Spring;                     // This should be okay
        MyClassWithEnum.Season localSeason = MyClassWithEnum.Season.Winter;     // This should NOT be okay
    }
}

It seems to me I am left to choose between defining the enum as public and letting any other class create instances of it, or making it private and not being able to set it from outside the class.

1

There are 1 answers

0
MichaC On BEST ANSWER

You do not instantiate Enums as if it where classes, therefore you cannot prevent someone to use it. With a class you could have a private ctor for example... That's obviously not possible with Enums.

So yes, your assumption is correct, either make it internal or private, or make it public... ;)

Btw, I cannot think about any good scenario where you want to hide the Enum while having a public property using the Enum, even if it where possible to do this.