Operators in C# Generics -
this question has answer here:
in c++ can write following:
template <typename t> void print(t a, t b) { cout<<a+b<<endl; } print(12,56) or print('c','s'); if overload operators user-define types(classes) can write:
person a, b; print(a,b); but in c# cant write operators such + - or * / why can't write this? , how can it(use operators in generic methods)?
how can it(use operators in generic methods)
generally, can't. operators, if used type parameter (say t), compiler cannot work out applicable overload use @ compile-time.
if write user-defined operators on base class (that on reference type non-sealed), can use them if have constraint. example system.uri non-sealed class overloads == operator. if do:
class test<t> t : uri { internal void method(t x, t y) { bool ok = x == y; } } the user-defined overload used. same other operators, of course.
but want pre-defined value types , pre-defined operators, example t numeric type (struct), , want == (equality) or * (multiplication) or << (bit shift on integer) or similar. not possible in c#.
it possible use dynamic instead of generic types, entirely different.
Comments
Post a Comment