Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to have a field named bool in C#?

I am sitting playing with elastic search from C#, and I wanted to create a query using an anonymous type in C# serialized to JSON. But I ran in to a problem as I need JSON that looks like this in one part:

{"bool": {<unimportant for question>}}

This would translate into a c# class that has a field named bool. Is this possible? (My guess is no...)

I think I will need custom serialization, or maybe elastic search provides some other alternative name for bool.

like image 268
Konstantin Avatar asked Feb 18 '23 18:02

Konstantin


2 Answers

If you want to name variables the same as keywords you can prefix them with @.

bool @bool = false;

I would avoid doing this in ALL circumstances where possible. It's just plain confusing.

like image 105
Paul Fleming Avatar answered Feb 21 '23 08:02

Paul Fleming


You can set the name in a [DataMember] attribute, but you need to use real classes (not anonymous).

using System;
using System.Collections;
using System.IO;
using System.Runtime.Serialization;
using System.Xml;

// You must apply a DataContractAttribute or SerializableAttribute 
// to a class to have it serialized by the DataContractSerializer.
[DataContract()]
class Enterprise : IExtensibleDataObject
{

    [DataMember(Name = "bool")]
    public bool CaptainKirk {get; set;}

    // more stuff here
}

More Info: http://msdn.microsoft.com/en-us/library/system.runtime.serialization.datamemberattribute.aspx

like image 23
Sklivvz Avatar answered Feb 21 '23 09:02

Sklivvz