C# Iterating Through an Enum? (Indexing a System.Array)

C# Iterating through an enum? (Indexing a System.Array)

Array values = Enum.GetValues(typeof(myEnum));

foreach( MyEnum val in values )
{
Console.WriteLine (String.Format("{0}: {1}", Enum.GetName(typeof(MyEnum), val), val));
}

Or, you can cast the System.Array that is returned:

string[] names = Enum.GetNames(typeof(MyEnum));
MyEnum[] values = (MyEnum[])Enum.GetValues(typeof(MyEnum));

for( int i = 0; i < names.Length; i++ )
{
print(names[i], values[i]);
}

But, can you be sure that GetValues returns the values in the same order as GetNames returns the names ?

Can you loop through an enum in C#?

You should be able to utilize the following:

foreach (MY_ENUM enumValue in Enum.GetValues(typeof(MY_ENUM)))
{
// Do work.
}

Iterate over enum?

Well, you can use Enum.GetValues:

foreach (GameObjectType type in Enum.GetValues(typeof(GameObjectType))
{
...
}

It's not strongly typed though - and IIRC it's pretty slow. An alternative is to use my UnconstrainedMelody project:

// Note that type will be inferred as GameObjectType :)
foreach (var type in Enums.GetValues<GameObjectType>())
{
...
}

UnconstrainedMelody is nice if you're doing a lot of work with enums, but it might be overkill for a single usage...

c# loop through all fields of enum assigning values from string array

Why not place the values onto the enum itself and then enumerate?

For example using System.ComponentModel Description attribute we can add that information to the enum itself such as:

public enum cardCreate
{
[Description("General Response")]
MsgType = 0,

[Description("V2.0")]
WSName = 2,

[Description("OmegaMan")]
ReplyTo = 3,

[Description("Windows 10")]
SourceSystem = 4,
}

So when we call a special method to enumerate the enum where we can extract that text and use it appropriately later such as:

myextensions.GetEnumValues<cardCreate>()
.Select (ceEnum => new
{
Original = ceEnum,
IndexValue = (int)ceEnum,
Text = ceEnum.GetAttributeDescription()
})

The dynamic entity will look like this after the projection (the select):

Sample Image

Sweet! Now we have all the information in a easy consumable entity which provides all the information needed.

What? You need more than a string description? Then create a custom attribute on the enum and have all items/types of data to return as needed. For that see my blog article C# Using Extended Attribute Information on Objects.


Here are the extension methods used in the above example:

public static class myextensions
{
public static IEnumerable<T> GetEnumValues<T>()
{
Type type = typeof( T );

if (!type.IsEnum)
throw new Exception( string.Format("{0} is not an enum.", type.FullName ));

FieldInfo[] fields =
type.GetFields( BindingFlags.Public | BindingFlags.Static );

foreach (var item in fields)
yield return (T)item.GetValue( null );
}

/// <summary>If an attribute on an enumeration exists, this will return that
/// information</summary>
/// <param name="value">The object which has the attribute.</param>
/// <returns>The description string of the attribute or string.empty</returns>
public static string GetAttributeDescription( this object value )
{
string retVal = string.Empty;
try
{
retVal = value.GetType()
.GetField( value.ToString() )
.GetCustomAttributes( typeof( DescriptionAttribute ), false )
.OfType<DescriptionAttribute>()
.First()
.Description;

}
catch (NullReferenceException)
{
//Occurs when we attempt to get description of an enum value that does not exist
}
finally
{
if (string.IsNullOrEmpty( retVal ))
retVal = "Unknown";
}

return retVal;
}

}

Enum as a parameter in a method, looping through the enum produces invalid cast

That usually means that your enum is not based on int, for example:

enum AgencyCodes : short {
...
}

You can't unbox an enum to the wrong type of value.

Iterating enum getting name and value

If I understand your question correctly

var dict = Enum.GetValues(typeof(MyEnum))
.Cast<int>()
.ToDictionary(x => Enum.GetName(typeof(MyEnum), x), x => x);


Related Topics



Leave a reply



Submit