What is the "Name=value" in [MyAttribute(Name=value)]

I don't know what phrasing to use to google this.

Consider this attribute:

 [MyAttribute(MyOption=true,OtherOption=false)]

What is the Name=value part? And how can I implement it in my own custom attributes?

Jon Skeet
people
quotationmark

It's specifying a property when creating an instance of the attribute.

Attributes can have constructor parameters and properties - this one is setting a property. Note that you can mix positional constructor arguments, named constructor arguments and properties, as shown in the sample below:

using System;
using System.Linq;
using System.Reflection;

[AttributeUsage(AttributeTargets.All)]
public class DemoAttribute : Attribute
{
    public string Property { get; set; }
    public string Ctor1 { get; set; }
    public string Ctor2 { get; set; }
    public string Ctor3 { get; set; }

    public DemoAttribute(string ctor1,
                         string ctor2 = "default2", 
                         string ctor3 = "default3")
    {
        Ctor1 = ctor1;
        Ctor2 = ctor2;
        Ctor3 = ctor3;
    }
}

[Demo("x", ctor3: "y", Property = "z")]
public class Test
{
    static void Main()
    {
        var attr = (DemoAttribute) typeof(Test).GetCustomAttributes(typeof(DemoAttribute)).First();
        Console.WriteLine($"Property: {attr.Property}");
        Console.WriteLine($"Ctor1: {attr.Ctor1}");
        Console.WriteLine($"Ctor2: {attr.Ctor2}");
        Console.WriteLine($"Ctor3: {attr.Ctor3}");
    }
}

Note the difference between : for a named constructor argument, and = for a property assignment.

The output of this code is

Property: z
Ctor1: x
Ctor2: default2
Ctor3: y

It's unfortunate that the C# specification calls both named constructor arguments and properties "named arguments" in this case :(

people

See more on this question at Stackoverflow