Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why const mytype _var = new mytype() doesn't work?

Tags:

c#

constants

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.

like image 708
Jack Avatar asked Dec 02 '22 22:12

Jack


2 Answers

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();
like image 109
DaveShaw Avatar answered Dec 24 '22 01:12

DaveShaw


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()
like image 32
Chris Avatar answered Dec 24 '22 00:12

Chris