Skip to Main Content
C# in a Nutshell
book

C# in a Nutshell

by Ben Albahari, Ted Neward, Peter Drayton
March 2002
Intermediate to advanced content levelIntermediate to advanced
864 pages
31h 8m
English
O'Reilly Media, Inc.
Content preview from C# in a Nutshell

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# 8.0 in a Nutshell

C# 8.0 in a Nutshell

Joseph Albahari, Eric Johannsen
C# 10 in a Nutshell

C# 10 in a Nutshell

Joseph Albahari
C# in a Nutshell, Second Edition

C# in a Nutshell, Second Edition

Peter Drayton, Ben Albahari, Ted Neward
Code like a Pro in C#

Code like a Pro in C#

Jort Rodenburg

Publisher Resources

ISBN: 0596001819Catalog PageErrata