Is it possible to check values ​​at compilation?

Is it possible for C # to have some kind of compilation checklist to ensure that the parameters for the functions are specific values?

For example, can I verify that the parameter of this function will always be greater than 10 at compile time?

void SomeFunction (1); <--- Compilation error here

+6
c #
source share
3 answers

See Code Contracts . He is powerful enough; It can be used both for checking runtime and for static checking. In addition, you can configure it to handle unproven contracts as warnings / compile-time errors.

void SomeFunction(int number) { Contract.Requires<ArgumentOutOfRangeException>(number > 10) ... } 
+6
source share

I do not know how to do this at compile time, you might be better off using an enumeration and provide only values ​​in this enumeration that exceed 10.

But of course, this limits you to specific values ​​that may not be what you want.

There are other options available to you:

  • Runtime error, such as an exception.
  • ignore runtime, for example, an if that exits a function for values ​​that are not in your range.

As a last resort, you can process the source code using another executable file that checks the values ​​passed to your function, but this will only work for calls that can be incremented to a constant argument. And, if they are persistent arguments, you will catch them at runtime during the testing phase long before your product gets a hundred feet from a client or beta tester. If your testing coverage is not down to scratch, but then this is another problem.

Otherwise, checking execution at runtime is your only option.

+3
source share

If this is not a very simple program, I think it is impossible. This sounds related to a stop problem .

0
source share

All Articles