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?
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;
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With