c# - How to restrict parameter types in generic methods -


say have 3 classes: a,b , c. each of these class have getvalue() method, returns int. want create method:

int gettotalvalue<t,r>(t c1, r c2) {   return c1.getvalue() + c2.getvalue() } 

obviously, won't work. not parameter types have getvalue() method. how restrict parameter types t , r, have have getvalue() method (that returns int)

have 3 implement interface contains getvalue method , constrain method using types.

public interface igetvalue {     int getvalue(); }  public class : igetvalue  // same b , c {     ... } 

then finally:

int gettotalvalue<t,r>(t c1, r c2) t : igetvalue, r : igetvalue {     return c1.getvalue() + c2.getvalue(); } 

update

as alex points out in him comment, method doesn't need generic though, can rewritten:

int gettotalvalue(igetvalue c1, igetvalue c2) {     return c1.getvalue() + c2.getvalue(); } 

Comments

Popular posts from this blog

angularjs - ADAL JS Angular- WebAPI add a new role claim to the token -

php - CakePHP HttpSockets send array of paramms -

node.js - Using Node without global install -