Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can I not use a "constant" within a switch statement within scope?

With this code:

public partial class Form1 : Form
{
    private static readonly int TABCONTROL_BASICINFO = 0;
    private static readonly int TABCONTROL_CONFIDENTIALINFO = 1;
    private static readonly int TABCONTROL_ROLESANDSECURITY = 2;
    private static readonly int TABCONTROL_INACTIVEINFO = 3;
. . .
int ActiveTabPage = tabControlWorker.SelectedIndex;
switch (ActiveTabPage) {
    case TABCONTROL_BASICINFO:
        if (currentNode == "NodeBuckingham") {
        } else if (currentNode == "NodeNamath") {
        } else if (currentNode == "NodeParsons") {
        } else {
        }
    break;

...I have to replace "TABCONTROL_BASICINFO" with "0", or I get, "A constant value is expected"

Heavens to Murgatroyd! Can't it look up and see that TABCONTROL_BASICINFO is 0?

like image 921
B. Clay Shannon-B. Crow Raven Avatar asked Mar 22 '12 23:03

B. Clay Shannon-B. Crow Raven


1 Answers

A readonly variable is not a constant. The value is not known at compile time, but rather can be initialized either in the declaration (as you have done) or in the class constructor (in this case, the static constructor for your class).

For more see

http://msdn.microsoft.com/en-us/library/acdd6hb7(v=vs.71).aspx

You can change it to:

private const int TABCONTROL_BASICINFO = 0; 

Unless you need to compute something to initialize the variable, declare it as const. It will be slightly more efficient.

like image 142
Eric J. Avatar answered Oct 21 '22 11:10

Eric J.