|
-
August 21st, 2009, 02:36 AM
#1
Numeric Based Generics Problem
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:
Code:
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!
-
August 21st, 2009, 04:08 AM
#2
Re: Numeric Based Generics Problem
There's no way to do this using generics. It's a known limitation.
www.monotorrent.com For all your .NET bittorrent needs
NOTE: My code snippets are just snippets. They demonstrate an idea which can be adapted by you to solve your problem. They are not 100% complete and fully functional solutions equipped with error handling.
-
August 21st, 2009, 04:16 AM
#3
Re: Numeric Based Generics Problem
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
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|