i have title poor able describe problem thing think of. anyway, suppose i've been given following enum:
public enum documenttype{ idcard=0, passport, driverslicense }
and have method accepts string , returns above enum:
public documenttype getdoctypebystring(string doctype){ switch (doctype) { case "id": return documenttype.idcard; case "pass" return documenttype.passport; //and on } }
now, if passed string not meet of switch conditions? silliest thing make return type object, that's hardly ever it. if enum mine, add additional value called "none" , return in case of no match, have no control on it. thought, whether possible constrain input values. far c# concerned, totally sure it's not possible, decided ask anyway. would recommend in case?
no can't. pattern used throw a
throw new argumentexception("doctype");
technically
throw new argumentoutofrangeexception("doctype");
would correct, haven't ever seen used outside "numeric" indexes.
for example, enum.parse
throw argumentexception
if use illegal values, , method seems similar that.
other option use enum.tryparse
pattern:
public static bool trygetdoctypebystring(string doctype, out documenttype documenttype) { switch (doctype) { case "id": documenttype = documenttype.idcard; return true; case "pass" documenttype = documenttype.passport; return true; } documenttype = default(documenttype); return false; }
Comments
Post a Comment