number of values in enum

P

puzzlecracker

What's the fastests way to find a number of values in enum.

I came up with this. but I think it's over kill.
enum Type
{
VAL1,
VAL2,
VAL3
}

int Enum.GetValues(typeof(TestType)).Length;

basically, I want to list available string representation of enum
members, and comma delimit them, and skip comma after the last
element. Output should look:

VAL1, VAL2, VAL3

Here is what I have thus far:
int =0;
foreach (Type type in Enum.GetValues(typeof(Type)))
{
Console.Write(type);
if(i++< Enum.GetValues(typeof(TestType)).Length)
Console.Write(", ");
}
}
Thanks
 
A

A Nonymous

How about:

Console.Write(String.Join(", ", Enum.GetNames(typeof(TestType))));

Using a slightly different example:

enum myType
{
alpha,
bravo,
charley
}

I assumed you wanted "alpha, bravo, charley"
not "0, 1, 2"

I believe GetValues returns the numeric value of the enumerated type, but
GetNames returns the names.
 
J

Jon Skeet [C# MVP]

Here is what I have thus far:
              int =0;
               foreach (Type type in Enum.GetValues(typeof(Type)))
                {
                    Console.Write(type);
                    if(i++< Enum.GetValues(typeof(TestType)).Length)
                        Console.Write(", ");
                }
            }

Here's a simpler way:

StringBuilder builder = new StringBuilder();
foreach (TestType element in Enum.GetValues(typeof(TestType))
{
if (builder.Length == 0)
{
builder.Append(", ");
}
builder.Append(element);
}
Console.Write(builder.ToString());

Prepending if it's not the first element means you don't need to know
whether or not it's the last element.

Of course you could generalise the above into a Join method:

string Join<T>(IEnumerable<T> elements, string separator)
or
string Join(IEnumerable<string> elements, string separator)

The latter would be used with a LINQ to Objects "select" projection to
convert an element into a string.

It's a shame that string.Join currently works in terms of arrays :(

Jon
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top