Any way to use a class extension method to support an interface method in C#?
Posted
by dudeNumber4
on Stack Overflow
See other posts from Stack Overflow
or by dudeNumber4
Published on 2010-05-28T17:25:24Z
Indexed on
2010/05/28
17:32 UTC
Read the original article
Hit count: 313
c#
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();
}
}
}
© Stack Overflow or respective owner