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.

Advertisement

5 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.

  2. One important thing that I by no means really seem to comprehend is why
    some blogposts are incredibly lousy – and yours is surely not!
    Appreciate your sharing an amazing short article with us!

  3. I am following this tutorial in 2021, thank you! I hope your daughter has beaten cancer and is doing well.

    1. Hey, glad this is still useful code nearly a decade later! She beat it before, but it came back, but she’s on track to be cancer free again in February! Thanks for the well wishes!

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 )

Facebook photo

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

Connecting to %s