How to work with attribute parameter in C#

Positional vs. Named Parameters

A positional parameter is linked by its position. Positional parameters must be specified in the order in which they appear. Named parameters are specified by assigning values to their names. For an attribute, you can also create named parameters. named parameters can be assigned initial values by using their names. A named parameter is supported by either a public field or property, which must not be read-only.

Here is the general form of an attribute specification that includes named parameters:

[attrib(positional-param-list, named-param1 = value, named-param2 = value, ...)]

Named attribute parameter

The following code uses a named attribute parameter to passin value to an attribute.


using System;  //w  ww .  j a va2  s  .c  om
using System.Reflection; 
  
[AttributeUsage(AttributeTargets.All)] 
public class MyAttribute : Attribute { 
  public string remark;
 
  public string supplement; 
 
  public MyAttribute(string comment) { 
    remark = comment; 
    supplement = "None"; 
  } 
 
  public string Remark { 
    get { 
      return remark; 
    } 
  } 
}  
 
[MyAttribute("This class uses an attribute.", 
                 supplement = "This is additional info.")] 
class UseAttrib { 
} 
 
class MainClass {  
  public static void Main() {  
    Type t = typeof(UseAttrib); 
 
    Console.Write("Attributes in " + t.Name + ": "); 
 
    object[] attribs = t.GetCustomAttributes(false);  
    foreach(object o in attribs) { 
      Console.WriteLine(o); 
    } 
 
    // Retrieve the MyAttribute. 
    Type tRemAtt = typeof(MyAttribute); 
    MyAttribute ra = (MyAttribute) 
          Attribute.GetCustomAttribute(t, tRemAtt); 
 
    Console.Write("Remark: "); 
    Console.WriteLine(ra.remark); 
 
    Console.Write("Supplement: "); 
    Console.WriteLine(ra.supplement); 
  }  
}

The code above generates the following result.





















Home »
  C# Tutorial »
    Custom Types »




C# Class
C# Struct
C# Interface
C# Inheritance
C# Namespace
C# Object
C# Delegate
C# Lambda
C# Event
C# Enum
C# Attribute
C# Generics
C# Preprocessor