Why are we allowed to use const with reference types if we may only assign null to them?

前端 未结 4 1382
暖寄归人
暖寄归人 2021-01-04 12:08

The question is actually very straightforward. The following code throws the exception right below it:

class Foo
{
    public const StringBuilder BarBuilder          


        
4条回答
  •  忘掉有多难
    2021-01-04 12:23

    From MSDN

    when the compiler encounters a constant identifier in C# source code (for example, months), it substitutes the literal value directly into the intermediate language (IL) code that it produces. Because there is no variable address associated with a constant at run time, const fields cannot be passed by reference and cannot appear as an l-value in an expression.

    Because reference types (other than null, and strings which are special) need to be constructed at run time, the above would not be possible for reference types.

    For reference types, the closest you can get is static readonly:

    class Foo
    {
        // This is not a good idea to expose a public non-pure field
        public static readonly StringBuilder BarBuilder = new StringBuilder();
        public Foo(){
        }
    }
    

    Unlike const substitution (in the calling code), static readonly creates a single shared instance of the reference type which has subtle differences if assembly versions are changed.

    Although the reference cannot (normally) be reassigned, it doesn't preclude calling non-pure methods on the StringBuilder (like Append etc). This is unlike consts, where value types and strings are immutable (and arguably should be "eternal").

提交回复
热议问题