#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;
Advertisement

About Sean
Software developer in the Twin Cities area, passionate about software development and sailing.

One Response to #319 – You Initialize a Constant Using an Expression

  1. Pingback: #586 – Default Values for Optional Parameters Must Be Constants « 2,000 Things You Should Know About C#

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: