Mats
Mats

Reputation: 11

default parameters and compile time constants

Why is SqlInt32.Null not considered a compile-time constant? Because I cant use it as the default value of a default parameter.

Upvotes: 1

Views: 200

Answers (1)

Fredrik Mörk
Fredrik Mörk

Reputation: 158379

SqlInt32.Null is a static readonly field, not a constant. This means that its value may not be known at compile time.

The main difference between a static readonly field and a const is that the const can be initialized only in the declaration of it, while the static readonly field can be initialized in the declaration or in a constructor.

Example:

public class SomeClass
{
    public static readonly int SomeValue;

    static SomeClass()
    {
        SomeValue = DateTime.Now.Millisecond;
    }
}

In the example above a static readonly field is initialized by the static constructor in a way that illuminates why it cannot be determined at compile time.

Upvotes: 5

Related Questions