8

I have read that C# allows local constants to be initialised to the null reference, for example:

const string MyString = null;

Is there any point in doing so however? What possible uses would this have?

slugster
  • 49,403
  • 14
  • 95
  • 145
Andy Bowskill
  • 1,734
  • 3
  • 18
  • 36

6 Answers6

6

My guess is because null is a valid value that can be assigned to reference types and nullable values types. I can't see any reason to forbid this.

There might be some far off edge cases where this can be useful, for example with multi targeting and conditional compilation. IE you want to define a constant for one platform but define it as null for another due to missing functionality.

Ex, of possible usefull usage:

#IF (SILVELIGHT)
    public const string DefaultName = null;
#ELSE
    public const string DefaultName = "Win7";
#ENDIF 
Pop Catalin
  • 61,751
  • 23
  • 87
  • 115
2

Indeed, you can initialize local const strings and readonly reference types to null, even though it seems to be redundant since their default value is null anyway.

However, the fact remains that null is a compile-time constant suitable enough to initialize strings and reference types. Therefore, the compiler would have to go out of its way in order to consider, identify and reject this special case, even though it's still perfectly valid from a language standpoint.

The merits of doing that would be disputable, and it probably wouldn't be worth the effort in the first place.

Frédéric Hamidi
  • 258,201
  • 41
  • 486
  • 479
  • @Derk-Jan, the special case I was referring to was the "local constant initialized to `null`" situation the questioner was wondering about. There are *many more*, I only meant that sometimes, even if a special case does not seem to make sense, it's still worth keeping its behavior in order to support a more general case. – Frédéric Hamidi May 10 '11 at 22:30
  • Yes, I understood and -stand what you said, but are there many more like these that don't make sense but exist by design? – Derk-Jan May 10 '11 at 22:32
  • 1
    @Derk-Jan, yes, many. For instance, you can define a class with a single parameterless constructor that does nothing, even though the compiler will generate the exact same one for you if you don't do that. That's also because preventing you from defining the constructor in that situation would not be worth the effort (and could understandably make you angry). – Frédéric Hamidi May 10 '11 at 22:38
  • Cool. I never thought about it that way - yet I know you can do it. We keep on learning everyday! – Derk-Jan May 10 '11 at 22:42
2

It could be used if you want to write code without keywords, if that strikes your fancy:

const string UninitializedSetting = null;

if (mySetting == UninitializedSetting)
{
    Error("mySetting string not initialized");
}
Gustavo Mori
  • 8,319
  • 3
  • 38
  • 52
David
  • 1,743
  • 1
  • 18
  • 25
1

Choosing to name a value (rather than using an in-place magic constant), using const, and setting to null are more or less orthogonal issues, although I agree that the venn diagram might have a very small area of overlap for the three :)

A case that I can think of is when you have as much or more throw-away data than you do code, but you want to ensure the values don't accidentally get changed while writing or maintaining your code. This situation is fairly common in unit tests:

[Test]
public void CtorNullUserName()
{
    const string expectedUserName = null;

    var user = new User(expectedUserName);

    Assert.AreEqual(expectedUserName, user.Name, "Expected user name to be unchanged from ctor");
}

You could arguably structure such code in a plethora of ways that didn't involve assigning null to a const, but this is still a valid option.

This might also be useful to help resolve method overloading issues:

public class Something
{
    public void DoSomething(int? value) { Console.WriteLine("int?"); }
    public void DoSomething(string value) { Console.WriteLine("string"); }
}

// ...

new Something().DoSomething(null); // This is ambiguous, and won't compile

const string value = null;
new Something().DoSomething(value); // Not ambiguous
Merlyn Morgan-Graham
  • 58,163
  • 16
  • 128
  • 183
0

If you use constants, for example, for configuration of your application then why not? The null value can represent a valid state - e.g. that a logger is not installed. Also note that when you declare a local constant, you can initialize it to a value given by global constant (which may be a more interesting scenario).

EDIT: Another question is, what are good situations for using const anyway? For configuration, you'd probably want a configuration file and other variables usually change (unless they are immutable, but then readonly is a better fit...)

Tomas Petricek
  • 240,744
  • 19
  • 378
  • 553
  • 2
    And if you initialize the logger, you can't set that value? – Derk-Jan May 10 '11 at 22:09
  • @Derk If it is state that changes, then I wouldn't use `const`. The example assumes that logger is a global setting that doesn't change at runtime. – Tomas Petricek May 10 '11 at 22:11
  • Do you have an example where that's the case? I can imagine using it as holder (future implementation). A good situation could be library settings (not configurable settings, but stuff you don't want hardcoded, or use alot in your libary), version numbers. `public/internal/private String const ErrorMessage = "Library Fault"`; – Derk-Jan May 10 '11 at 22:20
0

Besides the situations already pointed out, it may have to do with a quirk of the C# language. The C# Specification 3.0, section 8.5.2 states:

The type and constant-expression of a local constant declaration must follow the same rules as those of a constant member declaration (§10.4).

And within 10.4 reads as follows:

As described in §7.18, a constant-expression is an expression that can be fully evaluated at compile-time. Since the only way to create a non-null value of a reference-type other than string is to apply the new operator, and since the new operator is not permitted in a constant-expression, the only possible value for constants of reference-types other than string is null.

Gustavo Mori
  • 8,319
  • 3
  • 38
  • 52