Skip to Main Content
C# in a Nutshell, Second Edition
book

C# in a Nutshell, Second Edition

by Peter Drayton, Ben Albahari, Ted Neward
August 2003
Intermediate to advanced content levelIntermediate to advanced
928 pages
32h 1m
English
O'Reilly Media, Inc.
Content preview from C# in a Nutshell, Second Edition

Retrieving a Custom Attribute at Runtime

Retrieving attributes at runtime is done using reflection via one of System.Attribute’s GetCustomAttribute or GetCustomAttributes overloads. Here is an example that uses and inspects the CrossRefAttribute using GetCustomAttribute:

// XRefTest.cs - apply and inspect a CrossRefAttribute
// Compile with: csc /r:XRef.dll XRefTest.cs
using System;
class Bar { }
[CrossRef(typeof(Bar), Description="Foos often hang around Bars")]
class Foo {
  static void Main( ) {
    // Retrieve the custom attribute from type Foo
    Attribute attr =
      Attribute.GetCustomAttribute(typeof(Foo),      
                                   typeof(CrossRefAttribute));
    // Display the attribute.
    if (attr != null) {
      CrossRefAttribute cr = (CrossRefAttribute)attr;
      Console.WriteLine(cr);
    }
  }
}

This is one of the few circumstances where the difference between custom attributes and pseudocustom attributes becomes apparent, since pseudocustom attributes can’t be retrieved with GetCustomAttribute. Here is another example that uses reflection to determine which attributes are on a specific type:

using System;
[Serializable, Obsolete]
class Test {
  static void Main( ) {
    Type t = typeof(Test);
    object[ ] caarr = Attribute.GetCustomAttributes(t);
    Console.WriteLine("{0} has {1} custom attribute(s)",
                      t, caarr.Length);
    foreach (object ca in caarr)
      Console.WriteLine(ca);
  }
}

Although the Test class of the preceding example has two attributes specified, the sample produces the following output:

Test has 1 custom attribute(s) System.ObsoleteAttribute ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

C# in a Nutshell

C# in a Nutshell

Ben Albahari, Ted Neward, Peter Drayton
C# 7.0 in a Nutshell

C# 7.0 in a Nutshell

Joseph Albahari, Ben Albahari
C# Cookbook, 2nd Edition

C# Cookbook, 2nd Edition

Jay Hilyard, Stephen Teilhet
C# Cookbook

C# Cookbook

Joe Mayo

Publisher Resources

ISBN: 0596005261Catalog PageErrata