I am newbie to C#, and have a problem with understanding how should I implement an extension method of interface. I didn’t found any material about this issue. From the material I found about general extension methods in C# I expected the following simple demonstrating example work:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace testExtension
{
public interface IcheckThingsOut
{
bool x();
}
public static class extensionInterface
{
public static bool y(this IcheckThingsOut bla) { return true;}
}
public class implementInteface : IcheckThingsOut
{
bool IcheckThingsOut.x()
{
return true;
}
bool IcheckThingsOut.y()
{
return false;
}
}
}
But the compiler is still not satisfied. What did I miss, and what is the right syntax here (with the same semantics as the code)?
You have messed up the concepts of extension methods and interfaces. Extension methods are just a compiler convenient way of calling static methods on static classes. They do not extend the interface. What the compiler does when using an extensions method is:
… will be converted to:
So as you can see, y is not a method on your interface. This is why you can’t implement it explicitly in the implementation.