tags:

views:

334

answers:

4

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
A: 

Try this:

if (MY_CONST % 3 != 0) { int compilerError = 1 / 0; }
Timothy Khouri
That doesn't work.
Mark Cidade
True, fixed above.
Timothy Khouri
Please unmark this post as the answer, and use the one that I said below (the (MY_CONST % 3) one).
Timothy Khouri
+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
That will cause a runtime failure, not a compile-time failure.
Greg Beech
No, that will cause a compile-time error.
Timothy Khouri
it does raise an error if const % 3 == 0, but the question asker asked for when const % 3 != 0
Mark Cidade
David Arno
Sorry, ignore the MY_CONST % 3 == 3 option as that's impossible. Doh!
David Arno
+4  A: 

Timothy Khouri almost got it. It should be this:

int compilerError = 1 / (MY_CONST % 3 == 0 ? 1 : 0);
Mark Cidade
Even better. Very neat solution
David Arno
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?
No I just have enough rep to edit posts. I'm a rep newbie compared with the mighty maxidad though :)
David Arno