i try understand extension method concept in c#
, added interface :
public interface iextension { public static int multiple(this int a) { return * 2; } }
in main method
public static void main() { console.writeline("entrer un numero"); int =int.parse( console.readline()); a.multiple(); console.readkey(); }
i error in a.multiple();
indicates method not recognized.
even added static class implementing interface, same error.
how can fix problem?
extension methods must in static class
, not in interface
public static class myextension { public static int multiple(this int a) { return * 2; } }
and should print result:
console.writeline(a.multiple());
note extension method can't change value of a
(because int
value type), can return new value!.
check adding
console.writeline(a.multiple()); console.writeline(a);
just curiousity, in java 8 oracle added default methods interfaces: https://docs.oracle.com/javase/tutorial/java/iandi/defaultmethods.html little c# extension methods, defined inside interface. types implement interface can override them, otherwise "inherit" these default methods.
Comments
Post a Comment