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

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

Leave a comment