Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C#: Access Enum from another class

Tags:

c#

enums

I know I can put my enum at the Namespace area of a class so everyone can access it being in the same namespace.

// defined in class2
public enum Mode { Selected, New, }  

What I want is to access this enum from

public class1
{
   var class2 = new class2();
   // Set the Mode
   class2.Mode = Model.Selected
}

Is this somehow possible without using namespace area?

like image 537
Elisabeth Avatar asked Dec 14 '10 20:12

Elisabeth


People also ask

What C is used for?

C programming language is a machine-independent programming language that is mainly used to create many types of applications and operating systems such as Windows, and other complicated programs such as the Oracle database, Git, Python interpreter, and games and is considered a programming foundation in the process of ...

What is C full form?

Full form of C is “COMPILE”. One thing which was missing in C language was further added to C++ that is 'the concept of CLASSES'.

What language is C in?

C is a procedural language that provides no support for objects and classes. C++ is a combination of OOP and procedural programming languages. C has 32 keywords and C++ has 63 keywords. C supports built-in data types, while C++ supports both built-in and user-defined data types.


2 Answers

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.

like image 183
Mark Avenius Avatar answered Nov 03 '22 08:11

Mark Avenius


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.

like image 9
Rusty Nail Avatar answered Nov 03 '22 08:11

Rusty Nail