Solved

Enum to Array

Posted on 2009-07-16
6
1,066 Views
Last Modified: 2013-12-17
Hello,

If I have an enum like this...

public enum Things : int
{
      A = 1,
      B = 2,
      C = 4,
      D = 8.
      E = 16,
      F = 32
}


How can I then convert an int value of 11 (for example) into a Thing[] array which would contain Thing.A, Thing.B and Thing.D (1+2+8 = 11)

Cheers.

ETFairFax
0
Comment
Question by:ETFairfax
  • 4
6 Comments
 
LVL 3

Expert Comment

by:happel
ID: 24868014
I think you have to test for the bitflags and create/fill the array in a custom function.
Don't know a framework function which does this for you.

As bit test function I use they attached snippet..


        public static Boolean IsBitSet(Object bitField, Object checkBit)

        {

            return (((byte)(int)bitField & (byte)(int)checkBit) == (byte)(int)checkBit);

        }

Open in new window

0
 
LVL 39

Expert Comment

by:abel
ID: 24868055
It is actually much simpler then what happel proposes. You can use the FlagsAttribute and simply cast the value. The following statement prints "A, B, D":

[Flags()]

private enum MyTestEnum

{

    None = 0,

    A = 1, B = 2, C = 4, D = 8, E = 16, F = 32

}
 

private void testEnum()

{

    myTestEnum testEnum = (MyTestEnum) 11;

    Debug.WriteLine(testEnum);

}

Open in new window

0
 
LVL 39

Accepted Solution

by:
abel earned 125 total points
ID: 24868215
About using the Flags attribute:
 
 1. You should assign the values as powers of 2
 2. You should always assign "None = 0"
 3. Each enum variable of Flags type can have multiple values (flags)
 4. You can test flags with | (OR), & (AND) and ^ (XOR) as you would in any language
 5. Same for assignment
 6. You can use foreach or make it an array as follows:

// NOTE: this only works with the FlagsAttribute set on the enum!
 

// .NET 2.0 version:

private int[] EnumToArray(Enum someEnum)

{

    List<int> list = new List<int>();

    foreach (var it in Enum.GetValues(someEnum.GetType()))

    {

        if ((Convert.ToInt32(it) & Convert.ToInt32(someEnum)) != 0)

            list.Add((int)it);

    }

    return list.ToArray();

}
 

// .NET 3.5 version:

private int[] EnumToArray(Enum someEnum)

{

    return (from int en in Enum.GetValues(someEnum.GetType())

           where (en & Convert.ToInt32(someEnum)) != 0

           select en).ToArray();

}

Open in new window

0
How your wiki can always stay up-to-date

Quip doubles as a “living” wiki and a project management tool that evolves with your organization. As you finish projects in Quip, the work remains, easily accessible to all team members, new and old.
- Increase transparency
- Onboard new hires faster
- Access from mobile/offline

 

Author Closing Comment

by:ETFairfax
ID: 31604158
Excellent.  Very informative.  Ta very much!!
0
 
LVL 39

Expert Comment

by:abel
ID: 24868297
If you are lucky enough to be able to use .NET 3.5, consider creating an extension function for the Enum type, you can then use it for every Enum type in the same manner you are used to with other types that support Enumeration. Below is an example of a ToArray() extension function. You can call it like:

MyTestEnum someEnum = (MyTestEnum) 11;
int[] someArray = someEnum.ToArray();

This is of course the same idea, just a bit more convenient. ;-)

public static class EnumExtensions

{

    public static int[] ToArray(this Enum someEnum)

    {

        return (from int en in Enum.GetValues(someEnum.GetType())

                where (en & Convert.ToInt32(someEnum)) != 0

                select en).ToArray();

    }

}

Open in new window

0
 
LVL 39

Expert Comment

by:abel
ID: 24868301
Thanks for the follow up & the compliment!
0

Featured Post

How to run any project with ease

Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
- Combine task lists, docs, spreadsheets, and chat in one
- View and edit from mobile/offline
- Cut down on emails

Join & Write a Comment

In my previous article (http://www.experts-exchange.com/Programming/Languages/.NET/.NET_Framework_3.x/A_4362-Serialization-in-NET-1.html) we saw the basics of serialization and how types/objects can be serialized to Binary format. In this blog we wi…
A long time ago (May 2011), I have written an article showing you how to create a DLL using Visual Studio 2005 to be hosted in SQL Server 2005. That was valid at that time and it is still valid if you are still using these versions. You can still re…
Access reports are powerful and flexible. Learn how to create a query and then a grouped report using the wizard. Modify the report design after the wizard is done to make it look better. There will be another video to explain how to put the final p…
This video explains how to create simple products associated to Magento configurable product and offers fast way of their generation with Store Manager for Magento tool.

746 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

14 Experts available now in Live!

Get 1:1 Help Now