Skip to Main Content
Programming .NET Components, 2nd Edition
book

Programming .NET Components, 2nd Edition

by Juval Lowy
July 2005
Intermediate to advanced content levelIntermediate to advanced
644 pages
17h
English
O'Reilly Media, Inc.
Content preview from Programming .NET Components, 2nd Edition

Attributes

The ability to reflect methods and type information is a nice and intriguing technology, but reflection really shines and demonstrates its value when you use it in conjunction with .NET attributes. The idea behind attributes is simple: instead of coding functionality and features into your objects, you can add them by decorating your objects with attributes. The information in the attributes is added to the metadata about the objects that the compiler generates (its methods, base classes, etc.). .NET (or your custom tools) can read the metadata, look for the attributes, and then perform the functionality and add the features the attributes specify without the object’s or its developer’s involvement. For example, when you want to combine enums in a binary masking value, you can use the Flags attribute:

            [Flags]
    public enum WeekDay
    {
       Monday,
       Tuesday,
       Wednesday,
       Thursday,
       Friday,
       Saturday,
       Sunday,
    }

When the compiler sees the Flags attribute, it allows you to combine enum values with the | (OR) operator, as if they were integer powers of 2. For example:

    const WeekDay Weekend = WeekDay.Saturday|WeekDay.Sunday;

Another example is the Conditional attribute, defined in the System.Diagnostics namespace. This attribute directs the compiler to exclude from a build calls to any method it decorates if a specified condition isn’t defined:

    #define MySpecialCondition //usually DEBUG


    public class MyClass
    {
       public MyClass()
       {}
       [Conditional("MySpecialCondition")] public void MyMethod() {...} ...
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

Windows Forms Programming in C#

Windows Forms Programming in C#

Chris Sells
Metaprogramming in .NET

Metaprogramming in .NET

Jason Bock, Kevin Hazzard
.NET Windows Forms in a Nutshell

.NET Windows Forms in a Nutshell

Ian Griffiths, Matthew Adams

Publisher Resources

ISBN: 0596102070Supplemental ContentErrata Page