I have a private const int defined in a C# class. I want compilation to fail with an error if the value of this int mod 3 != 0. How can I accomplish this?
+2
A:
Although there is an #error pre-processor directive for generating compile-time errors, there is no way for it to be based on the existence of a const value. It only works with compiler symbols, like "DEBUG", for which a value can't be assigned.
Mark Cidade
2008-10-29 22:18:58
A:
Try this:
if (MY_CONST % 3 != 0) { int compilerError = 1 / 0; }
Timothy Khouri
2008-10-29 22:18:59
That doesn't work.
Mark Cidade
2008-10-29 22:21:14
True, fixed above.
Timothy Khouri
2008-10-29 22:22:25
Please unmark this post as the answer, and use the one that I said below (the (MY_CONST % 3) one).
Timothy Khouri
2008-10-29 22:27:26
+1
A:
Sorry, that code I said below won't work, but this will :)
int pointless = 1 / (MY_CONST % 3);
The reason why this will work is because you'll get a compile time, "can't devide by zero" error. Your "MY_CONST" field will have to be anything that (once modded by 3) will not be equal to zero.
Timothy Khouri
2008-10-29 22:20:55
it does raise an error if const % 3 == 0, but the question asker asked for when const % 3 != 0
Mark Cidade
2008-10-29 22:26:31
David Arno
2008-10-29 22:27:56
Sorry, ignore the MY_CONST % 3 == 3 option as that's impossible. Doh!
David Arno
2008-10-29 22:29:15
+4
A:
Timothy Khouri almost got it. It should be this:
int compilerError = 1 / (MY_CONST % 3 == 0 ? 1 : 0);
Mark Cidade
2008-10-29 22:24:57
Yep, this is what I wanted.Strikes me as odd that one user can edit another user's answer and not leave a trace of what he originally wrote. David, are you some kind of moderator or something?
2008-10-29 22:35:24
No I just have enough rep to edit posts. I'm a rep newbie compared with the mighty maxidad though :)
David Arno
2008-10-29 22:36:54