c# - extension is not recognized on dynamic field -


i used extension on decimal fields:

public static class extensions {     static system.globalization.cultureinfo _cultinfo = system.globalization.cultureinfo.invariantculture;     public static string converttostringwithpointdecimal(this decimal source)     {         return source.tostring(_cultinfo);     } } 

but when have dynamic parameter, contains class type decimals in it, cannot use extension on fields.

test setup:

public class testdecimalpropclass {     public decimal prop1 { get; set; }     public decimal prop2 { get; set; } }  private void tryextensionondynamicbutton(object sender, eventargs e) {     testdecimalpropclass _testdecimalpropclass = new testdecimalpropclass { prop1 = 98765.432m, prop2 = 159.753m };     testextension(_testdecimalpropclass); }  private void testextension(dynamic mysource) {     decimal harddecimal = 123456.789m;     string resultoutofharddecimal = harddecimal.converttostringwithpointdecimal();      decimal prop1decimal = mysource.prop1;     string resultoutofprop1decimal = prop1decimal.converttostringwithpointdecimal();      string resultoutofprop2 = mysource.prop2.converttostringwithpointdecimal(); }} 

both resultoutofharddecimal , resultoutofprop1decimal return correct string value, when code hits mysource.prop2.converttostringwithpointdecimal(), error:"'decimal' not contain definition 'converttostringwithpointdecimal'", while prop2 of decimal type.

any thoughts?

kind regards,

matthijs

extension methods don't work dynamics.

because c# compiler can't resolve type of mysource.prop2 @ build time, can't know can use extension method.

however, can still explicitly call method:

string resultoutofprop2 = extensions.converttostringwithpointdecimal(mysource.prop2); 

(like static method)

see also: extension method , dynamic object answers jon skeet , eric lippert.


Comments

Popular posts from this blog

html - How to style widget with post count different than without post count -

How to remove text and logo OR add Overflow on Android ActionBar using AppCompat on API 8? -

javascript - storing input from prompt in array and displaying the array -