views:

96

answers:

3

how to initialize a variable of data type integer, in c sharp. the problem is the variable has to store an integer with values ranging from 1 to 4.

+2  A: 

int x = 1;

You may be wanting an enum that is constrained values.

rerun
+3  A: 

You could use an enum, which typed as an Int32 (int) by default. E.g.

public enum MyEnum
{
    FirstValue,
    SecondValue,
    ThirdValue,
    FourthValue
}

Obviously you can call the enum whatever you like, and give the four values meaningful names. Then you can just initialise an instance as so:-

var myValue = MyEnum.FirstValue;
AdamRalph
An enumeration does not constrain values, since all integer values are stil valid. The following wil work just fine:var MyValue = (MyEnum)(-1);
Chris
I know that, but at least an enum states the intention.
AdamRalph
+2  A: 

For a static member variable assign at declaration:

public class MyClass 
{
    Static int myVar = 1;
}

For a local method variable assign at declaration:

void MyFunc ()
{
    int myVar = 1;
}

For member variable assign at declaration or in the constructor

public class MyClass
{
    int myVar;

    public MyClass()
    {
        myVar = 1;
    }
}

On the other hand, to restrict to the range 1..4 you have to protect it with a property set like:

public class MyClass
{
    int myVar = 1;

    public int MyVar
    {
        get { return myVar; }
        set 
        { 
            if( value < 1 || value > 4) throw new Exception();
            myValue = value; 
        }

    }
}
Simeon Pilgrim