Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accessing property of dynamic object when property name is a keyword

Tags:

json

c#

dynamic

I am trying to access a property of a JSON object like this:

using Newtonsoft.Json.Linq;

dynamic myJsonData = JObject.Parse("{ \"out\":123, \"xyz\": 456 }");
Console.WriteLine(myJsonData.xyz); //works          
Console.WriteLine(myJsonData.out); //compiler error ";" expected

However, the last line does not compile.

Is there a simple way to use the dynamic property to get the value of "out" even though out is a keyword in C#?

like image 625
Philipp Avatar asked Sep 06 '25 17:09

Philipp


1 Answers

It should be solved by adding @ before the reserved keyword:

Console.WriteLine(myJsonData.@out);

Here is a quote from MSDN:

Keywords are predefined, reserved identifiers that have special meanings to the compiler. They cannot be used as identifiers in your program unless they include @ as a prefix. For example, @if is a valid identifier but if is not because if is a keyword.

like image 195
dotnetom Avatar answered Sep 08 '25 10:09

dotnetom