Extension method for enumerators

Extensions methods are pretty powerful thing because we can extend existing types without inheriting from them. I don’t know developers who want to extend string or int or other basic types offered by .Net Framework.

There was a project lately where I had to use existing code from internet. There was extremely chaotic and confusing error handling logic and try-catch blocks appeared even in places where one little if has been enough.

One place where I found good use for extension methods was paring strings to enums by their name. The original code was something like this.


FieldTypeEnum fieldType;
try
{
   
Type enumType = typeof(FieldTypeEnum
);
   
object parsedType = Enum
.Parse(enumType, fieldName);
    fieldType = (
FieldTypeEnum
)parsedType;
}

catch
{
    fieldType =
FieldTypeEnum.TextType;
}

Well, we can see that this code is not very nice and short. Try-catch blocks should be used carefully because in the case of exceptions they may eat resources and hit system’s performance hard. It is always better to avoid try-catch as far as you can.

So, what this code does? It tries to find enum value by the name that is assigned to the value. If value doesn’t exist then default value is used. To accomplish this task without try-catch I wrote the following extension method.


public static class EnumExtensions
{
   
public static bool ContainsName(this Enum e, string
name)
    {
       
string[] namesArray = Enum
.GetNames(e.GetType());
        Int32 index =
Array
.IndexOf(namesArray, name);
       
return (index > -1);
    }
}

This methods checks if there is given name in given enumerator and returns true if name is found in enum names array. If name is not found then, of course, false is returned. Let’s see now how the previous code looks like if there is no try-catch block used.


FieldTypeEnum fieldType = new FieldTypeEnum();
if
(fieldType.ContainsName(fieldName))
{
   
object parsedType = Enum
.Parse(fieldType.GetType(), fieldName);
    fieldType = (
FieldTypeEnum
)parsedType;
}

else
    fieldType = FieldTypeEnum.TextType;

We can also write the body of if this way.


FieldTypeEnum fieldType = new FieldTypeEnum();
if
(fieldType.ContainsName(fieldName))
    fieldType = (
FieldTypeEnum)Enum.Parse(fieldType.GetType(), fieldName);
else
    fieldType = FieldTypeEnum.TextType;

Now we have pretty short and easily readable code instead of try-catch we used before. Also we are protected against overhead that may be caused by invalid enum constant names.


2 thoughts on “Extension method for enumerators

Leave a Reply

Your email address will not be published. Required fields are marked *