John Liu .NET

View Original

Food for thought: C# Extension Methods

Disclaimer, I have not tested any of the following code.

Write the following extension method:

public static int ToInt(this A a)
{
return Int32.Parse(a.ToString());
}

public class A
{
}
Now, say the class designer of A implemented it's own ToInt method.
public class A
{
public int ToInt(){ return 0; }
}

What happens now to the extension method?
My guess is that it would shadow the class method.


Now, assuming that the extension method shadows the class method, how could one access the class method in the extension method?

public static int ToInt(this A a)
{
return a.ToInt(); // infinite recursion?
}