Special Characters in Anonymous Types

asp.net, asp.net-mvc-3, c#

Solution

You have to stick to the rules! Your code won't compile because you are writing this as an anonymous type in code (not as strings) so the keys have to be identifiers in the language.

The language has rules. An identifier has to start with a valid `identifier-start-character`, defined:

A Unicode character of classes Lu, Ll, Lt, Lm, Lo, or Nl

As per this rule:

http://www.jaggersoft.com/csharp_grammar.html#identifier-start-character

Using this table, the third column tells us that '$' is in the 'Sc' class, so you can't use it.

http://www.unicode.org/Public/UNIDATA/UnicodeData.txt

If I were you I'd do one of three things:

- fix your API specification so it doesn't rely on keys that are not valid identifiers in the language you are using (painful)

- write a simple translation layer that re-writes your JSON before it gets sent (messy)

Problem

I want to create an anonymous type with a special character in the name of a variable For instance I have this: ``` new { status = "Active" } ``` I would like something like ``` new { status = "Active", $exists = true } ``` This eventually serializes to JSON, so I know I can use JObject or something like that, but it would be much easier as an anonymous type.

Original source