Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Enum.Parse(), surely a neater way?

Tags:

c#

enums

asp.net

Say I have an enum,

public enum Colours {     Red,     Blue } 

The only way I can see of parsing them is doing something like:

string colour = "Green"; var col = (Colours)Enum.Parse(typeOf(Colours),colour); 

This will throw a System.ArgumentException because "Green" is not a member of the Colours enum.

Now I really hate wrapping code in try/catch's, is there no neater way to do this that doesn't involve me iterating through each Colours enum, and doing a string comparison against colour?

like image 439
maxp Avatar asked Mar 07 '10 01:03

maxp


People also ask

How does enum parse work?

Parse(Type, String, Boolean) Converts the string representation of the name or numeric value of one or more enumerated constants to an equivalent enumerated object. A parameter specifies whether the operation is case-insensitive.

What is enum parse?

The Parse method in Enum converts the string representation of the name or numeric value of enum constants to an equivalent enumerated object.


1 Answers

Use Enum.IsDefined() first, to save yourself from wrapping in a try/catch. It will return a boolean value of whether or not the input is a valid member of that enum.

like image 168
statenjason Avatar answered Sep 19 '22 18:09

statenjason