Throw compiler error based on const value
Hi all,
I would like to throw a compiler error based on a const value. The situation is that this constant is used on several places in the code. However, in some places the code needs adaption if this const value is changed. When this const value is changed by the programmer I would like to warn/error him of the consequences.
In C++ this can be done with a #define, but in C# you can not use #define for this.
Can this be accomplished in another way?
thank you,
Jef
Re: Throw compiler error based on const value
The only way I can think of is to put code in like:
if (MyConstValue != 7)
throw new UpdateThisAreaOfCodeBecauseTheValueChangedException ();
which probably means you don't want const values.
Re: Throw compiler error based on const value
I had thought of a solution like this as well, but this is an execution time exception. C++ allows you to have a compile time exception.
A simplified example of my situation: several arrays that are all equal in lenght and at certain point in the code you need to show the values in several labels.
Code:
const int length = 3;
int[] array1 = int[length];
int[] array2 = int[length];
int[] array3 = int[length];
for(int i=0; i < length; i++)
{
...
}
label1.Text = array1[0].ToString();
label2.Text = array1[1].ToString();
label3.Text = array1[2].ToString();
changing length to 2 would cause an error at runtime for label3. C++ allows you to prevent this with a compiler error.
regards,
Jef
Re: Throw compiler error based on const value
I would simply not write code like you have there. It is fragile and pointless considering that you have collection classes to use instead of raw arrays, and you probably should not be indexing by constant values like that anyway. I know you said it was a simplified example, but I don't think it is valid at all because the solution there is to simply write better code.
Do you really need this? Are your coworkers so careless that they would go about changing things without understanding what they do? Is a comment above the const value not enough?