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 const
must be something that can be resolved at Compile Time.
new foo();
will be executed at runtime.
You probably want to use the readonly
keyword to ensure that it cannot be initialised outside of the constructors:
private readonly foo f = new foo();
const indicates that the value is known at compile time. Because new allocates an object (which is impossible if the program is not running), you cannot set a const to a new object. you can achieve something somewhat simmilar like this:
static readonly Foo foo = new Foo()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With