Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

enums in C# - assignment

Tags:

c#

enums

How does one do this in c#?

Let's say that myclass has :

private enum Days{};


1) How does one add data to the enum inside the myclass with the help of the constructor? As in :

myclass my = new myclass(Monday,Friday);

so that the enum inside the class gets the "Monday, Friday" properties.


2) Can one also make a property for an enume inside the class once it is initialized ? For example :

my.Days = new enum Days(Tuesday); //where the old settings are replaced.

EDIT:

What I want to do is following:

Have an enum in the main class, like enum Days{Monday,Tuesday,Wednesday,Thursday,Friday};

I would also have something inside the myclass (enum?) so that I can assign some values from Days enum to myclass internal (enum?) with only some but not all of the values in the Days enum.

So that I can get a myclass which contains an (enum?) with "Monday,Tuesday", while some myclass222 contains (enum?) "Friday" etc.

I don't know if the enum is the correct way to do this inside the myclass classes ?

like image 362
Milan Avatar asked Mar 18 '10 19:03

Milan


2 Answers

Your question is somewhat vague, but if you are actually asking how to construct an enum where the values can be combined, the answer is to decorate it with the Flags attribute:

[Flags]
public enum Days
{
    None = 0,
    Monday = 1,
    Tuesday = 2,
    Wednesday = 4,
    Thursday = 8,
    Friday = 16,
    Saturday = 32,
    Sunday = 64
}

Now, if you have some member of the type Days, you can assign a combined value to it:

Days someDays = Days.Monday | Days.Wednesday;

Update
On request; here is how to check whether a certain value is set:

bool wednesdayIsSet = (someDays & Days.Wednesday) == Days.Wednesday;

In response to the question on how to create a member of the enum in one class when the enum is defined in another class, that would look like this:

public class SomeClass
{
    [Flags]
    public enum Days
    {
        None = 0,
        Monday = 1,
        // and so on
    }
}

public class SomeOtherClass
{
    public SomeClass.Days SomeDays { get; set; }
}
like image 156
Fredrik Mörk Avatar answered Sep 19 '22 19:09

Fredrik Mörk


1) You can't. The enum must be defined at compile time

It seems like you might look for an AttributeCollection instead. (have a look at Fredrik Mörk's answer, that it what I was trying to talk about ;) )

2) my.Days = Days.Tuesday

like image 28
citronas Avatar answered Sep 19 '22 19:09

citronas