Code Snippet - How to Use Extension with Enum
2014/05/031 min read
bookmark this
Table of Contents
Introduction
In C# you sometimes need to convert an enum to an int value. Here is a simple extension method to make that easier.
The Problem
Given the following enum:
public enum NameType
{
Undefined,
TypeA,
TypeB,
TypeC,
TypeD,
TypeE = 99
}
You could write like this:
(int)NameType.TypeE
But what if you could just write like this:
NameType.TypeE.ToInt();
The Extension Method
Here is an Enum Extension Class that makes this possible. This is just a basic example.
public static class EnumHelper
{
public static int ToInt(this Enum enumValue)
{
object val = Convert.ChangeType(enumValue, enumValue.GetTypeCode());
return Convert.ToInt32(val);
}
}
Conclusion
Using extension methods on enums in C# provides a cleaner syntax for common operations like converting to int. You can extend this pattern to add other useful helpers to your enum types.