c# - Calculate absolute value of numbers using Generic class -
static void main(string[] args) { absvalue<int> abs = new absvalue<int>(); absvalue<double> absdouble = new absvalue<double>(); abs.x = -5; absdouble.x = 65.3; console.writeline("integer absolute value: {0}", math.abs(abs.x)); console.writeline("double absolute value: {0}", math.abs(absdouble.x)); console.readline(); } }
i don't think correctly, seems work. can please give me advise, how can create better?
class absvalue<t> { public t x; }
there's not clean way wrap math.abs
generic function, because 1) function not generic instead designed overloads each numeric type, , 2) creating generic restraint numeric types not possible in .net1.
even if did you'd still have have giant switch
statement phone call proper math.abs
overload.
i think i'd find different problem solve beginner - 1 not easy learning exercise.
1 you can close constraining parameter struct, icomparable, iformattable
, doesn't purchase much you'd have cast utilize operators or framework math functions.
c# .net generics
No comments:
Post a Comment