Any way to use a class extension method to support an interface method in C#?
- by dudeNumber4
Console app below compiles, but the interface cast fails at run time. Is there an easy way to make this work?
namespace ConsoleApplication1
{
class Monkey
{
public string Shock { get { return "Monkey has been shocked."; } }
}
static class MonkeyExtensionToSupportIWombat
{
public static string ShockTheMonkey( this Monkey m )
{
return m.Shock;
}
}
interface IWombat
{
string ShockTheMonkey();
}
class Program
{
static void Main( string[] args )
{
var monkey = new Monkey();
Console.WriteLine( "Shock the monkey without the interface: {0}", monkey.Shock );
IWombat wombat = monkey as IWombat;
Console.WriteLine( "Shock the monkey with the interface: {0}", wombat.ShockTheMonkey() );
Console.ReadLine();
}
}
}