Why is it not possible to use implicit conversion when calling an extension method?
Here is the sample code:
using System;
namespace IntDecimal
{
class Program
{
static void Main(string[] args)
{
decimal d = 1000m;
int i = 1000;
d = i; // implicid conversion works just fine
Console.WriteLine(d.ToNumberString()); // Works as expected
Console.WriteLine(i.ToNumberString()); // Error
Console.WriteLine(ToNumberString2(i)); // Implicid conversion here works just fine
}
static string ToNumberString2(decimal d)
{
return d.ToString("N0");
}
}
public static class Ext
{
public static string ToNumberString(this decimal d)
{
return d.ToString("N0");
}
}
}
Error i get: 'int' does not contain a definition for 'ToNumberString' and the best extension method overload 'Ext.ToNumberString(decimal)' requires a receiver of type 'decimal'
As we can see. An implicit conversion from int to decimal exists and works just fine when we do not use it as an extension method.
I know what I can do to get things working, But what is the technical reason that there is no implicit cast possible when working with extension methods?
((decimal)i).ToNumberString()
or create a new overload for the extension method with anint
. – Mcallister