0

So, I'm aware of the concept of Named Parameters and Optional Parameters within C#. This is the same idea, but it uses different syntax.

When passing, from the Newtonsoft.Json library, arguments to the JsonObject attribute, you're presented with a massive list of optional named parameters. These named parameters have no order, and so must be called using that same pattern as proper named parameters, however, normal C# named parameters syntax is, varName: varValue and this syntax follows the more expected varName = varValue

[JsonObject( 
    ItemNullValueHandling = NullValueHandling.Ignore
    , ItemRequired = Required.AllowNull
    , Title = "Tester" )]
public class Jsonifier {
    public String Name {get;set;}
    public String Value {get;set;}
}

What is going on here that is different from the Named Parameters syntax and how do I replicate this behavior ?

  • 4
    You aren't calling any method in the code snippet, you are adding an attribute to your class. Attributes are something completely different than methods – UnholySheep Dec 07 '21 at 20:13
  • 1
    They're properties of the attribute class, not named parameters, and they are actually *assigned* after construction, so `=` was an appropriate syntax choice. These are different from the attribute class's *constructor arguments*, which use the `:` as you were expecting, if named. – madreflection Dec 07 '21 at 20:15
  • 3
    See here: [Attributes #positional-and-named-parameters](https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/language-specification/attributes#positional-and-named-parameters) – Peter B Dec 07 '21 at 20:17
  • 5
    C# has had the ability to set Attribute properties in constructor expressions (which is what `[SomeAttribute()]` is) since the beginning. Mostly because that's the only way you can set the properties of an attribute. Eventually, that capability was added to all classes, so now you can do this `var xyz = new XyzClass {prop1=42, prop2="yup"}`. The different syntax was likely related to what was possible to do without breaking existing code. When they added named parameters, they needed to pick another syntax, so they use the colon `:` – Flydog57 Dec 07 '21 at 20:22
  • Following up on the comment of @Charlieface, None of the [`JsonObjectAttribute` constructors](https://www.newtonsoft.com/json/help/html/Overload_Newtonsoft_Json_JsonObjectAttribute__ctor.htm) actually have optional parameters. So your question is really about how to apply attributes with optional values. – dbc Dec 13 '21 at 22:40

0 Answers0