0

I used this 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 I have a dynamic parameter, that contains a class type with decimals in it, I cannot use the extension on those 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 and resultOutOfProp1Decimal return a correct string value, but when the code hits mySource.prop2.ConvertToStringWithPointDecimal(), I get this error:"'decimal' does not contain a definition for 'ConvertToStringWithPointDecimal'", while prop2 is of decimal type.

Any thoughts?

Kind regards,

Matthijs

user369122
  • 792
  • 3
  • 13
  • 33

1 Answers1

2

Extension methods don't work with dynamics.

Because the C# compiler can't resolve the type of mySource.prop2 at build time, it can't know that it can use the extension method.

However, you can still explicitly call the method:

string resultOutOfProp2 = Extensions.ConvertToStringWithPointDecimal(mySource.prop2);

(like any static method)

See also: Extension method and dynamic object with answers from Jon Skeet and Eric Lippert.

Community
  • 1
  • 1
Benoit Blanchon
  • 13,364
  • 4
  • 73
  • 81