Alvaro Lourenço
Alvaro Lourenço

Reputation: 1341

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

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

This code will output the error CS0836: Anonymous types cannot be used in this expression. But if you remove const it will run ok.

I'm really just trying to understand. Why can't anonymous type be used in constant declarations?

More specifically: What other way should be used to declare a constant like that?

Upvotes: 5

Views: 1717

Answers (2)

canton7
canton7

Reputation: 42225

From MSDN

Constants can be numbers, Boolean values, strings, or a null reference

So the fact that there's an anonymous type here is not relevant: if you were using a custom class you would get a similar error.

Consider using a static readonly field instead of const for these cases.

That said, having a field of type object in this situation is questionable: no-one who references the field is going to be able to access Prop1 or Prop2, so the field is arguably useless.

Consider defining a custom class (not an anonymous type) which contains your two properties, and using that instead, e.g. private static readonly Foo foo = new Foo(10, 20);

Upvotes: 7

George Lica
George Lica

Reputation: 1816

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

Upvotes: 2

Related Questions