Why can't nullables be declared const?
c#, constants, null, nullable
Solution
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;
Problem
``` [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