This line of code works, but I'm not sure why it does.

[JsonProperty("id", Required = Required.Always)]

To me this seems to be setting a value of a Property in the JsonProperty class. Is this unique only to Attributes and declaring attributes?

Looking at the JsonProperty class I can see that the constructor is written like so

 public JsonPropertyAttribute(string propertyName);

Again, how does this work? It seems to run contrary to how I've written C# for the past year.. Is it magic within the Attribute class or is it actually a feature of C#?

1 Answers

Avi Meltser On Best Solutions

These are Named Arguments and they are not unique to Attributes.

C# 4 introduced them:

Named arguments enable you to specify an argument for a particular parameter by associating the argument with the parameter's name rather than with the parameter's position in the parameter list.

C# 6.0 introduced Named Parameters which are the equivalent for Attributes.

Attribute classes can have positional parameters and named parameters. Each public instance constructor for an attribute class defines a valid sequence of positional parameters for that attribute class.