c# - Interface with generic parameter vs Interface with generic methods -


let's have such interface , concrete implementation

public interface imyinterface<t> {     t my(); }  public class myconcrete : imyinterface<string> {     public string my()     {         return string.empty;     } } 

so create myconcrete implementation strings, can have 1 more concrete implementation int. , that's ok. let's say, want same thing, generic methods, have

public interface imyinterface2 {     t my<t>(); }  public class myconcrete2 : imyinterface2 {     public string my<string>()     {         throw new notimplementedexception();     } } 

so have same imyinterface2, defines generic behavior means of t my<t>(). in concrete class want implement my behavior, concrete data type - string. c# doesn't allow me that.

my question why cannot that? in other words, if can create concrete implementation of myinterface<t> myclass : myinterface<string> , stop genericness @ point, why can't generic method - t my<t>()?

your generic method implementation has generic well, has be:

public class myconcrete2 : imyinterface2 {     public t my<t>()     {         throw new notimplementedexception();     } } 

why can't my<string>() here? because interface contract needs method, called type parameter t , have fulfill contract.

why can't stop genericness in point? because cause situations following:

class declarations:

public interface imyinterface2 {     t my<t>(t value); }  public class myclass21 : imyinterface2 {     public string my<string>(string value) { return value; } }  public class myclass22 : imyinterface2 {     public int my<int>(int value) { return value; } } 

usage:

var item1 = new myclass21(); var item2 = new myclass22();  // both implement imyinterface2, can put them list var list = new list<imyinterface2>(); list.add(item1); list.add(item2);  // iterate list , call method foreach(imyinterface2 item in list) {     // item imyinterface2, have my<t>() method. choose t int , call value 2:     item.my<int>(2);      // how work item1, has my<string> implemented? } 

Comments