Click to See Complete Forum and Search --> : Numeric Based Generics Problem


Grofit
August 21st, 2009, 02:36 AM
Hey,

Ive got a problem with an object that im trying to keep generic. It is pretty much the same as a typical system.drawing.Point class but instead is a generic, so it could be of a type int, float, double, uint whatever.

Now making the class is easy enough, but now im writing the static methods which are causing problems as i dont know of any way to constrict the type to always be anything from byte to double, and when i try to write the subtract method:


public static void Sub(Point<T> a, Point<T> b)
{ return new Point<T>(a.X-b.X, a.Y-b.Y); }


i get the error that generic T cannot be subtracted from T, which is fair enough as it could be anything in its current state, so is there any way to get around this problem or restrict it to numeric based types, even if its just int or float. Im using .net 2.0 at the moment but have access to .net 3.5 if needed. Havent got 4 installed at the moment as im sure that has an INumeric interface which may be another solution...

Any help would be great!

Mutant_Fruit
August 21st, 2009, 04:08 AM
There's no way to do this using generics. It's a known limitation.

Grofit
August 21st, 2009, 04:16 AM
Yeah, just been looking online and noticed alot of people saying same thing...

I thought it would have been a common sort of usage with Generics, ive seen the argument that generics shouldnt be used like this because they are generic and should be able to take anything... but thats just silly, why would they put in the where clause if they didnt want to give you that sort of control over your generics.

In my eyes if it can save you re-writing N methods by making it generic then its going to make code easier to maintain and update.

I can get round the issues using Dynamic, but im currently only on .net 2 so im out of luck :(