c# - Can generics be used to collapse these methods? -


i have 2 methods similar things different return type (string vs int)

here are:

private static string loadattributestring(this xelement xmlelement,                                            string attributename, string defaultvalue) {     try         {return xmlelement.attribute(attributename).value;}     catch (exception)         {return defaultvalue;} }  private static int loadattributeint(this xelement xmlelement,                                      string attributename, int defaultvalue) {     try         {return int.parse(xmlelement.attribute(attributename).value);}     catch (exception)         {return defaultvalue;} } 

is possible use generics combine these 1 method? (i tried , failed.)

note: fine having 2 different methods. expand knowledge of generics. thought ask if possible.

yes. use convert.changetype instead of specific parsing function.

private static t loadattribute<t>(this xelement xmlelement,                                    string attributename,                                    t defaultvalue)                                   t : iconvertible {     try     {         return (t)convert.changetype(             xmlelement.attribute(attributename).value,              typeof(t));     }     catch (exception)     {         return defaultvalue;     } } 

by way, catching exception bad idea. want hide null reference bugs?

as generality of jared's answer, can't resist rewriting mine mere overload his:

private static t loadattribute<t>(this xelement xmlelement,                                    string attributename,                                   t defaultvalue)                                    t : iconvertible {     return loadattribute(         xmlelement,          attributename,          x => (t)convert.changetype(x, typeof(t)),          defaultvalue); } 

Comments

Popular posts from this blog

java - SNMP4J General Variable Binding Error -

sql server - python to mssql encoding problem -

windows - Python Service Installation - "Could not find PythonClass entry" -