c# - Use Generic class with SqlDataReader GetValue -


i have code works ok database no null values

public t getfield<t>(sqldatareader dr, string fieldname) {     return (t)dr.getvalue(dr.getordinal(fieldname)); } 

then want control dbnull values, because exist in tables , upgraded function this:

public t getfield<t>(sqldatareader dr, string fieldname) t : new() {     var value = dr.getvalue(dr.getordinal(fieldname));        return value dbnull ? new t() : (t)value; } 

but now, cannot ask getfield<string> because string has no constructor 0 parameters.

i have tried create function abstract one, no restrictions , string type this

public string getfield<string>(sqldatareader dr, string fieldname) {     var value = dr.getvalue(dr.getordinal(fieldname));        return value dbnull ? "" : value.tostring(); } 

but answer ambiguous definitions, because t includes string, restriction applied.

i create independent functions each datatype, rather prefer abstract solution because way cleaner.

did miss something?

thanks!

here's 1 approach:

public t getfield<t>(sqldatareader dr, string fieldname) {     var value = dr.getvalue(dr.getordinal(fieldname));     return value dbnull ? default(t) : (t) value; } 

this has added benefit of working nullable types. you'd call as:

string x = foo.getfield<string>(reader, "field") ?? ""; 

which deliberately contrived in case -- jon's version default suits better if want other null returned.


Comments

Popular posts from this blog

java - Oracle EBS .ClassNotFoundException: oracle.apps.fnd.formsClient.FormsLauncher.class ERROR -

c# - how to use buttonedit in devexpress gridcontrol -

nvd3.js - angularjs-nvd3-directives setting color in legend as well as in chart elements -