c# - How to convert an arbitrary object to enum? -


i have object. either long or string, simplify code let's assume that.

i have create method tries convert object provided enum. so:

public object toenum(type enumtype, object value) {     if(enumtype.isenum)     {         if(enum.isdefined(enumtype, value))         {            var val = enum.parse(enumtype, (string)value);            return val;         }     }     return null; } 

with strings works well. numbers causes problems, because default underlying type enum int, not long , isdefined throws argumentexception.

of course can many checks, conversions or try-catches.

what want have clean , small code that. ideas how make readable , simple?

it feels me want handle 3 cases:

  • input right type
  • strings
  • integers in various types

i believe want valid input:

public object toenum(type enumtype, object value) {     if (value == null)     {         throw new argumentnullexception("value");     }     if (enumtype == null)     {         throw new argumentnullexception("type");     }     if (!enumtype.isenum)     {         return false;     }     string valuestring = value string;     if (valuestring != null)     {         return enum.isdefined(enumtype, value) ? enum.parse(enumtype, valuestring) : null;     }     if (value.gettype() == enumtype)     {         return value;     }     // appears handle longs etc     return enum.toobject(enumtype, value); } 

however, return value of right type undefined values. if don't want that, change last part to:

object candidate = enum.toobject(enumtype, value); return enum.isdefined(enumtype, candidate) ? candidate : null; 

also, still throw exception if pass in floating point number, or that. if don't want behaviour, you'll need have set of types do want accept, , check against first.


Comments

Popular posts from this blog

html - Sizing a high-res image (~8MB) to display entirely in a small div (circular, diameter 100px) -

java - IntelliJ - No such instance method -

identifier - Is it possible for an html5 document to have two ids? -