On Thu, 16 Oct 2008 13:26:02 -0700, puzzlecracker <ironsel2000@gmail.com>
wrote:
Quote:
What's the fastests way to find a number of values in enum.
I think you found it.
Quote:
I came up with this. but I think it's over kill.
enum Type
{
VAL1,
VAL2,
VAL3
}
>
int Enum.GetValues(typeof(TestType)).Length;
Why is that overkill? (Not counting that I don't think you should be
using the name "Type", given that it conflicts with the System.Type type).
Quote:
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(", ");
}
}
I think you meant "if(++i< Enum.GetValues(typeof(TestType)).Length)" or
possibly "if(i++< Enum.GetValues(typeof(TestType)).Length - 1)". But
anyway...
Technically speaking you don't actually need to know the length:
bool fFirst = true;
foreach (Type type in Enum.GetValues(typeof(Type)))
{
if (fFirst)
{
fFirst = false;
}
else
{
Console.Write(", ");
}
Console.Write(type);
}
If you really wanted to use the length, but were concerned that getting it
would be expensive, you would get the length just once (it's not going to
change during the loop, after all):
int itypeLast = Enum.GetValues(typeof(Type)).Length - 1;
for (int itype = 0; itype < Enum.GetValues(typeof(Type)).Length;
itype++)
{
Console.Write(type);
if (itype < itypeLast)
{
Console.Write(", ");
}
}
Of course, you could avoid both the boolean or the comparison against the
last element index:
for (int itype = 0; itype < Enum.GetValues(typeof(Type)).Length;
itype++)
{
if (itype 0)
{
Console.Write(", ");
}
Console.Write(type);
}
Finally, note: in the for() loops above, because the compiler is able to
notice that the Length property is invariant during the loop, it retrieves
it only once at the beginning of the loop. If for some reason you
couldn't count on that optimization (for example, you were dealing with a
collection that the compiler can't verify as invariant for the loop, but
which you know is), you could also retrieve the length outside the loop
and use that.
Pete