Can you have a property name containing a dash

Is it possible to create an object with a property name that contains a dash character?

I am creating an anonymous object so that I can serialize it to Json using Json.Net and one of the properties I need contains a '-' dash character.

An example of what I want is:

var document =  {
    condtions = new {
        acl = "public-read",
        bucket = "s3-bucketname",
        starts-with = "test/path"
    }
};

I know I could replace the dash with underscores when creating the object and then replace them in the serialized string afterwards, but wanted to know if there is a way in the language to do this without this workaround.

Answers


You can't do this with anonymous objects; field names must be valid identifiers. You could instead use a Dictionary, which Json.Net should serialise just as easily as an anonymous object:

var document = new {
    conditions = new Dictionary<string, string>() {
        { "acl", "public-read" },
        { "bucket", "s3-bucketname" },
        { "starts-with", "test/path" }
    }
};

Not in c#, no. However most serializers allow you to customise this - often via attributes. IIRC with JSON.NET you want [JsonProperty("starts-with")] to specify the name. However you can't use attributes on anonymous types, so you may need to define a class with the properties (and attributes) the you desire.


Unfortunately, that's not possible, because the language would not be able to differentiate the two following expressions:

condition.starts-with;    // Read "starts-with" property.
condition.starts - with;  // Read "starts" property and subtract "with" variable.

Need Your Help

numpy sum of squares for matrix

python numpy

I do have a matrix with observations in rows (measurements at differnt pH) with data points as columns (concentration over time). So one row consists of differnt data points for one pH.

Validate Enum Values

c# validation enums

I need to validate an integer to know if is a valid enum value.