CodeBlanks Logo Icon CodeBlanks

Named and positional parameters

C# course · Advanced · Lesson 52/83

Learn named and positional parameters in attributes.

Positional and named parameters

Attribute usage takes two kinds of parameters. Positional parameters go to the constructor in order and are required. Named parameters are assigned to writable properties and are optional. Syntax: [Attr("pos", Named = 5)].

Positional parameters map to the attribute constructor's parameter list. Named parameters are written as Name = value and come after the constructor arguments, comma-separated. Named ones are assigned to the class's public settable properties.

Positional parameters

Positional parameters are the arguments of the attribute constructor. They are required and order matters. They come before named parameters. Example: for the constructor public InfoAttribute(string name), [Info("Data")] is positional.

Multiple positional parameters are comma-separated. If you mix positional and named, all positionals come first, then named: [Info("Data", Priority = 3)]. Order does not matter among named parameters.

Exercise Use positional and named together

Apply [Info("Data", Priority = 3)] to the Sample class below. In Main, read it with Attribute.GetCustomAttribute(typeof(Sample), typeof(InfoAttribute)) as InfoAttribute and print attr.Priority with Console.WriteLine.

Show example solution
var attr = Attribute.GetCustomAttribute(typeof(Sample), typeof(InfoAttribute)) as InfoAttribute; Console.WriteLine(attr.Priority);
Example solution:
using System;

[AttributeUsage(AttributeTargets.Class)]
public class InfoAttribute : Attribute
{
    public string Name { get; set; }
    public int Priority { get; set; }
    public InfoAttribute(string name) { Name = name; }
}

[Info("Data", Priority = 3)]
class Sample { }

class Program
{
    static void Main()
    {
        var attr = Attribute.GetCustomAttribute(typeof(Sample), typeof(InfoAttribute)) as InfoAttribute;
        Console.WriteLine(attr.Priority);
    }
}

Test yourself

  1. Where does a named parameter go?

    • To a writable property
    • To the constructor
    • To a static field
    • To a read-only property
    Show answer

    To a writable property — Correct. A named parameter is assigned to a writable property.

  2. Complete the named parameter

    [My("test", ____ = 5)]
    Show answer
    [My("test", Count = 5)]
  3. Match the parameter kind to its target

    Positional
    Constructor parameter
    Named
    Property assignment
    Optional
    Named and optional
    Mandatory
    Positional required

All lessons in Advanced