Extension methods in combination with interfaces
suggest changeAn extension method on an interface keeps the implementation outside the class. A class gains that method by implementing the interface.
public interface IInterface
{
string Do();
}
public static class ExtensionMethods{
public static string DoWith(this IInterface obj){
//does something with IInterface instance
}
}
public class Classy : IInterface
{
// this is a wrapper method; you could also call DoWith() on a Classy instance directly,
// provided you import the namespace containing the extension method
public string Do(){
return this.DoWith();
}
}
use like:
var classy = new Classy();
classy.Do(); // will call the extension
classy.DoWith(); // Classy implements IInterface so it can also be called this way
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents