Is it possible to constraint a method so that it receives only int
, double
, long
or other numerical types that has the usual numerical operations ( such as +
,-
,*
,/
) defined?
Asked
Active
Viewed 3.8k times
24

Graviton
- 81,782
- 146
- 424
- 602
-
2You could probably create an interface with those operations, and wrap the numerical data types in something that implements that interface. It probably wont be the most efficient, and will use a bunch of custom stuff, but it will solve that problem if that is the most important thing. – Nick Larsen Apr 15 '10 at 12:53
2 Answers
21
This is not possible currently.
Also, see this question for a possible workaround
-
5The fact that there's no common base type for the numeric types is really unfortunate. – Matti Virkkunen Apr 15 '10 at 12:50
-
2
-
1
-
1
-
1While this link may answer the question, it is better to include the essential parts of the answer here and provide the link for reference. Link-only answers can become invalid if the linked page changes. – ProgramFOX Mar 08 '14 at 11:18
17
No, unfortunately there is no such restriction possible. The closest you can get is using struct, IConvertible
as generic type constraint.
You may want to read this question though.
-
2I am surprised as to why this from Lucero was not voted. Using structs is the closest one can restrict the type parameter to be of value types – AlwaysAProgrammer Apr 15 '10 at 13:22