Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Constrain const variable at compile time

Tags:

c#

.net

I have some const field as in the following code, and I need its value to be at least 1. Is there a way to enforce the compiler to not allow values less than 1?
const int number = 2;

like image 472
XPhyro Avatar asked Sep 18 '25 22:09

XPhyro


1 Answers

This seems like overkill. Since this can only be changed by a developer, why not just leave a message for them? Something like this should do the trick:

const int number = 2;     // Don't EVER set this to less than
                          // one, you have been warned.
                          // <Insert reason here>.

Make sure the <Insert reason here> bit has enough detail so that the developer is convinced not to try. For example:

// Don't EVER set this to less than one, doing so will result in
// the furlongs-per-fortnight calculation ending up as a negative
// number, meaning the delay calls will treat it as a very large
// POSITIVE number, effectively halting the thread forever.
// We COULD change it so that it checks and clamps the value but,
// since this is time critical image rendering code, we don't want
// ANYTHING to slow it down (we have a customer requirement to
// be able to render 3000 frames per second, or we'll suffer
// monetary penalties).

If a developer then chooses to ignore your warning, it's on them.

In any case, since any developer capable of ignoring that warning will also be capable of removing whatever restrictions you've placed on the value, those restrictions will be no more useful or secure than the warning comment.


If you must have a check for this, you can simply put something like this into your code, somewhere where it's executed only once (keep in mind that ArgumentOutOfRangeException may not necessarily be the best exception, I'm just using it as an example):

if (number < 1) {
    throw new ArgumentOutOfRangeException("number", "Must be >= one");
}

It's not a compile time check but it will probably be caught by one of (assuming you do these (and, if not, why not?)):

  • your automated unit tests; or
  • your peers when they review your code before committing.

Worst case (assuming you do neither), it'll be caught by the first developer that tries to use it after the errant change is inflicted on them, at which point the person who inflected it should be ready to explain themselves :-)

like image 199
paxdiablo Avatar answered Sep 21 '25 10:09

paxdiablo