Extension methods in combination with C# with Example



Extension methods in combination with C# with Example

interfaces 
It is very convenient to use extension methods with interfaces as implementation can be stored outside of class and 
all it takes to add some functionality to class is to decorate class with 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 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 

0 Comment's

Comment Form

Submit Comment