I’m very curious looking for an explanation why the following code isn’t allowed in C#.NET designer:
const foo f = new foo();
It give the following error message:
‘f’ is of type ‘ConsoleApplication1.foo’. A const field of a reference
type other than string can only be initialized with null.
The question is: Why? Can someone explain this const requirement?
Thanks in advance.
Because a
constmust be something that can be resolved at Compile Time.new foo();will be executed at runtime.You probably want to use the
readonlykeyword to ensure that it cannot be initialised outside of the constructors: