Is it possible to check values at compilation?
Is it possible in C# to have some sort of check list when compiling to ensure parameters to functions are certain values?
For example, can I check that the parameter of this function is always greater 开发者_开发知识库than 10 at compile time?
void SomeFunction(1); <--- Compile error here
Take a look at Code Contracts. It's quite powerful; it can be used for both runtime checking and static verification. In addition, you can configure it to treat unproven contracts as compile-time warnings / errors.
void SomeFunction(int number)
{
Contract.Requires<ArgumentOutOfRangeException>(number > 10)
...
}
I don't know of any way to do this at compile time, you may be better off using an enumeration and only providing values in that enumeration that are above 10.
But, of course, this limits you to specific values which may not be what you want.
There are other options available to you such as:
- runtime error, like throwing an exception.
- runtime ignore, such as an
if
statement that exits the function for values that aren't in your range.
At a pinch, you could process the source code with another executable which examines values passed into you function, but that will only work for calls that can be bolied down to a constant argument. And, if they're constant arguments, you will catch them at runtime during the testing phase, long before your product gets within a hundred feet of a customer or beta tester. Unless your testing coverage is not up to scratch but then that's a different problem.
Otherwise, runtime checking is your only option.
If it isn't a very simple program I think this is impossible. It sounds related to the Halting problem.
精彩评论