Force a C# method to pass only positive parameters?

.net, c#, oop

Solution

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:

- You can validate the argument value, throwing an exception if it's invalid. (This is a much better idea than using `Math.Abs` to try to "fix" invalid input.)

- You could use Code Contracts to indicate to other code that the parameter should have a non-negative value, and it will attempt to prove that everywhere you call the method, the value will be non-negative. This won't be enforced by the C# compiler, but it can still be a build-time procedure.

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.

Problem

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.

Original source