Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extension methods for both double and double?

Tags:

c#

I am trying to write an extension method which accepts both double and double?.

public static class ExtensionMethod
{
    public static string ToFixedScale(this double? value)
    {
        return value.HasValue ? (Math.Truncate(value.Value * 100) / 100).ToString("0.00") : null;
    }
}

It works fine for dobule?, however it doesn't work for double. Is there a way I can use this extension method for both double and double?.

EDIT : As all the user suggested to have two extension methods as double and double? are not of not same type, I am sure this might be the stupid question but is there a way where extension method accepts multiple types?

like image 886
Manish Makkad Avatar asked Dec 21 '16 07:12

Manish Makkad


Video Answer


1 Answers

Nullable<double> and double are two different types. While there does exist an implicit conversion between these types, extension methods for one will not be found by the other's type. You will need to overload your method with a version that accepts a double for a parameter:

public static class ExtensionMethod
{
    public static string ToFixedScale(this double value)
    {
        return Math.Truncate(value * 100) / 100).ToString("0.00");
    }

    public static string ToFixedScale(this double? value)
    {
        return value.HasValue ? ToFixedScale(value.Value) : null;
    }
}
like image 136
lc. Avatar answered Sep 17 '22 22:09

lc.