c# - Using Generic T to Determine Compiler-Chosen Overload -


i have following code. plan getsetting() call appropriate version of fromstring(), depending on type of t.

public static t getsetting<t>(persistedsetting setting, t defaultvalue = default(t)) {     return fromstring(registrysettings.getsetting(setting.tostring()) string, defaultvalue); }  private static string fromstring(string value, string defaultvalue) {     return value ?? string.empty; }  private static int fromstring(string value, int defaultvalue) {     int i;     return int.tryparse(value, out i) ? : defaultvalue; }  private static decimal fromstring(string value, decimal defaultvalue) {     decimal d;     return decimal.tryparse(value, out d) ? d : defaultvalue; }  private static bool fromstring(string value, bool defaultvalue) {     bool b;     return bool.tryparse(value, out b) ? b : defaultvalue; } 

however, on line calls fromstring(), compile error:

the best overloaded method match 'articlemanager.persistedsettings.fromstring(string, string)' has invalid arguments

the compiler assumes fromstring(string, string). there way have use appropriate overload t?

edit:

i'm not sure best guess @ happening overloading determined @ compile time, while getsetting() doesn't know type until run time. but, if that's problem, how 1 go solving particular problem?

overload selection happen @ compile time. that's issue.

you can make happen @ runtime using dynamic:

return fromstring(registrysettings.getsetting(setting.tostring()) string, (dynamic)defaultvalue); 

read more on msdn: using type dynamic (c# programming guide)

or can make method non-generic method , have set of overloads getsetting, e.g.

public static int getsetting(persistedsetting setting, int defaultvalue = default(int)) {     return fromstring(registrysettings.getsetting(setting.tostring()) string, defaultvalue); } 

Comments

Popular posts from this blog

matlab - "Contour not rendered for non-finite ZData" -

delphi - Indy UDP Read Contents of Adata -

javascript - Any ideas when Firefox is likely to implement lengthAdjust and textLength? -