c# - Generic Method Return Type as Type parameter -


i have extension method working ok cast string values various types, looks this:

public static t totype<t> (this string value, t property)     {         object parsedvalue = default(t);         type type = property.gettype();          try         {             parsedvalue = convert.changetype(value, type);         }         catch (argumentexception e)         {             parsedvalue = null;         }          return (t)parsedvalue;     } 

i'm unhappy way looks when calling method, however:

myobject.someproperty = stringdata.totype(myobject.someproperty); 

specifying property obtain property's type seems redundant. rather use signature this:

public static t totype<t> (this string value, type type) { ... } 

and have t end type of type. make calls cleaner:

myobject.someproperty = stringdata.totype(typeof(decimal)); 

when try call way, however, editor complains return type of extension method can't infered usage. can link t type argument?

what missing?

thanks

is looking for? i've added catch cases cast isn't valid also

decimal = stringname.totype<decimal>();  public static t totype<t>(this string value) {      object parsedvalue = default(t);      try      {          parsedvalue = convert.changetype(value, typeof(t));      }      catch (invalidcastexception)      {          parsedvalue = null;      }      catch (argumentexception)      {          parsedvalue = null;      }      return (t)parsedvalue; }  

edit

a shortcut approach fix anton's comment

if (typeof(t).isvaluetype)    return default(t); 

Comments

Popular posts from this blog

javascript - DIV "hiding" when changing dropdown value -

Does Firefox offer AppleScript support to get URL of windows? -

android - How to install packaged app on Firefox for mobile? -