Why can't C # anonymous type be used when declaring constants?

private const object foo = new {Prop1 = 10, Prop2 = 20};

      

This code displays the error CS0836: Anonymous types cannot be used in this expression

. But if you uninstall const

it will work fine.

I'm just trying to figure it out. Why can't anonymous type be used in persistent declarations?

In particular: what other way should I use to declare such a constant?

+3


source to share


2 answers


From MSDN

Constants can be numbers, booleans, strings, or null reference

So the fact that the anonymous type doesn't matter here: if you used a custom class, you'll get a similar error.



Consider using a field static readonly

instead const

for these cases.

So the presence of a type field in this case object

is questionable: no one who refers to the field will be able to access Prop1

or Prop2

, so the field is probably useless.

Consider defining a custom class

(not anonymous type) that contains your two properties and using that for exampleprivate static readonly Foo foo = new Foo(10, 20);

+6


source


As far as I know, in C # you can only declare a set of predefined primitive types as constants: you can find more information here: https://msdn.microsoft.com/en-us/library/ms173119.aspx . An anonymous type is just an immutable reference type that is automatically written by the compiler, so it is like a normal reference type that you can write at any time.



+2


source







All Articles