#320 – The Constant Expression for a Reference-Typed Constant Must Be Null

The declaration of a constant may use a reference type as the type of the constant.  However, reference types other than string are seldom seen.  The compiler needs to evaluate the value of the constant at compile time.  This means that the constant expression cannot invoke a method on a reference type.  The only valid value in the expression is therefore null.

            // Marginally useful
            const Dog TheNullDog = null;

            // Not allowed - Compile-time ERROR
            const Dog ConstantBob = new Dog("Bob");

One exception to this rule about only using null in a constant expression for a reference type is the string (System.String) class.  A constant of type string may be initialized with a string literal.

            // string constants can be initialized, although they are reference types
            const string MyDogsName = "Kirby";
Advertisement

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

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 )

Twitter picture

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

Facebook photo

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

Connecting to %s

%d bloggers like this: