Uncategorized

Get enums by index, get index of an enum value in an enum

I like using enums for simple selections. I feel it makes my code clean. Over time you may feel that parts of your program have “outgrown” enums and you may need to switch to classes to handle extra logic. You can, but with attributes, you do not have to. If a parameter must be one of a few choices, even if it’s nullable, then use an enum.

I’m writing an iPhone app using Monotouch where I am displaying enum options to be picked from a list. The functions I am listing below help greatly in dealing with indices on enums.

 

public static TEnum GetEnumByIndex(int index)
{
var etype = typeof(TEnum);
if (!etype.IsEnum)
throw new ArgumentException(“‘TEnum’ must be of an enum type.”);
var enums = Enum.GetValues(typeof(TEnum));
if (index > enums.Length)
throw new ArgumentOutOfRangeException(“index”);
TEnum option = (TEnum)enums.GetValue(index);
return option;
}

public static int? GetIndexOfEnumValue(TEnum value)
{
var etype = typeof(TEnum);
if (!etype.IsEnum)
throw new ArgumentException(“‘TEnum’ must be of an enum type.”);
var enums = Enum.GetValues(typeof(TEnum));
int i = 0;
foreach (object e in enums)
{
if (((TEnum)e).Equals(value))
return i;
i++;
}
return null;
}

In other news, my daughter is doing really well with her chemo treatments. Hopefully she will be cancer free in a few years! See my wife’s page detailing my daughter’s battle with Acute Lymphoblastic Leukemia.

Advertisements

3 thoughts on “Get enums by index, get index of an enum value in an enum

  1. I will immediately take hold of your rss feed as I can’t in finding your email subscription hyperlink or e-newsletter service. Do you have any? Kindly let me realize so that I may just subscribe. Thanks.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s