I want to force my method to only accept an integer parameter if it is positive. If the method is passed a negative integer it should throw a compile time error. What is the best way to achieve this?
Currently I am using Math.Abs(Int)
inside the method, but I want the error to be at compile time.
Just make the parameter a uint
or a ushort
. That will prevent negative input at compile-time. It won't prevent 0, however... I assume you're really after non-negative input rather than strictly positive input.
If your method has to accept a signed parameter, then:
Math.Abs
to try to "fix" invalid input.)If you go with the exception approach, then you should also have a comprehensive set of unit tests around the code calling your method - and that code should validate its inputs as well, of course.
See more on this question at Stackoverflow