Why can't nullables be declared const?

2019-04-04 05:04发布

[TestClass]
public class MsProjectIntegration {
    const int? projectID = null;
    // The type 'int?' cannot be declared const
    // ...
}

Why can't I have a const int??

Edit: The reason I wanted a nullable int as a const is because I'm just using it for loading some sample data from a database. If it's null I was just going to initialize sample data at runtime. It's a really quick test project and obviously I could use 0 or -1 but int? just felt like the right data structure for what I wanted to do. readonly seems like the way to go

5条回答
一夜七次
2楼-- · 2019-04-04 05:15

It's not just nullables; only types built into the runtime can be declared const (from memory, it's bools, the various types of int, floats/doubles, and strings).

Why? Because the value gets embedded directly into the assembly at compile time, and there's no way to embed user-defined types.

The readonly keyword should do what you need, however. By contrast with const, any readonly fields get initialized at runtime rather than compile time, so they can be initialized with more or less any expression you want.

Edit: as Eric Lippert points out, it's not this straightforward. For instance, const decimal works.

This:

private const decimal TheAnswer = 42;

...compiles (well, Reflectors) to this:

[DecimalConstant(0, 0, (uint) 0, (uint) 0, (uint) 42)]
private static readonly decimal TheAnswer;
查看更多
做自己的国王
3楼-- · 2019-04-04 05:15

You may want to consider using the "readonly" modifier instead.

consts are evaluated at compile time, whereas readonlys are enforced at run time. Instances of complex types cannot be compiled into the assembly, and so must be created at runtime.

查看更多
贼婆χ
4楼-- · 2019-04-04 05:20

You can't have a const reference type (or a struct), therefore you can't have a const int? which is really just a Nullable<int>.

You can mark it as readonly

readonly int? projectID = null;

Then it can't be modified outside the class constructors.

查看更多
来,给爷笑一个
5楼-- · 2019-04-04 05:23

http://en.csharp-online.net/const,_static_and_readonly

Constants must be of an integral type (sbyte, byte, short, ushort, int, uint, long, ulong, char, float, double, decimal, bool, or string), an enumeration, or a reference to null.

Since classes or structures are initialized at run time with the new keyword, and not at compile time, you can't set a constant to a class or structure.

Since nullable is a struct, the above quote is the reason why.

查看更多
姐就是有狂的资本
6楼-- · 2019-04-04 05:34

You're basically saying:

I have a class with a projectId field that may or may not have a value, but that in fact NEVER has a value, it's is always undefined.

From a logical point of view... the declaration itself makes no sense.

查看更多
登录 后发表回答