Thursday, March 10, 2005

String to Enumeration Value C#

Here is code, that will take a string value and return the corresponding enumeration value. //t - type of the enumeration static object StringToEnum( Type t, string Value ) { foreach ( FieldInfo fi in t.GetFields() ) if ( fi.Name == Value ) return fi.GetValue( null ); // We use null because enumeration values are static throw new Exception( string.Format("Can't convert {0} to {1}", Value, t.ToString()) ); }

No comments: