C#: Access Enum from another class

Aaron's answer is very nice but I believe there is a much better way to do this:

public static class class1
{
    public void Run()
    {
        class2.Mode mode = class2.Mode.Selected;

        if (mode == class2.Mode.Selected)
        {
            // Do something crazy here...
        }
    }
}

public static class class2
{
    public enum Mode
    { 
        Selected, 
        New
    } 
}

No point over complicating this. It is a simple task.

All the Best

Chris.


You can declare an enum outside of a class:

namespace MyNamespace
{
    public enum MyEnum
    {
        Entry1,
        Entry2,
    }
}

And then you can add using MyNamespace; where it needs to be used.


If you are trying to do what is described below it will not work...

    public class MyClass1
    {
        private enum Mode { New, Selected };
        public Mode ModeProperty { get; set; }
    }

    public class MyClass2
    {
        public MyClass2()
        {
            var myClass1 = new MyClass1();

            //this will not work due to protection level
            myClass1.ModeProperty = MyClass1.Mode.
        }
    }

What you could do however is below, which will work...

    public interface IEnums
    {
        public enum Mode { New, Selected };
    }

    public class MyClass1
    {
        public IEnums.Mode ModeProperty { get; set; }
    }

    public class MyClass2
    {
        public MyClass2()
        {
            var myClass1 = new MyClass1();

            //this will work
            myClass1.ModeProperty = IEnums.Mode.New;
        }
    }

Tags:

C#

Enums