#319 – You Initialize a Constant Using an Expression

You initialize a constant in C# using either a literal or an expression that resolves to the correct type.

    public class Dog
    {
        const string Demeanor = "friendly";
        const int NumberOfLegs = 4;
        const double OneThird = 1.0 / 3.0;

You can also use the value of another constant in a constant expression.

        const int NumberOfLegs = 4;
        const int NumberOfEyes = 2;
        const int EyeAndLegCount = NumberOfLegs + NumberOfEyes;

The constant expression must be able to be resolved at compile time, so you can’t use something that is not a constant.  This includes variables and also includes the results of method calls.

        static int NumLegs = 4;   // Not a constant

        // Error: The expression being assigned to 'ConsoleApplication2.Dog.LegsPlusOne' must be constant
        const int LegsPlusOne = NumLegs + 1;
Advertisements