Chapter 27. C attributes


Chapter 27. C# attributes

C# attributes [1] , [2] are a new feature with no equivalent in Java. [3] Put simply, C# attributes are comment-like tags enclosed in square brackets used to label or mark a class, interface, assembly, method, event, field, delegate, or method parameter in codes. Attributes enable these entities in source codes to be tagged with additional declarative information. These tags can be 'read' during runtime using C#'s built-in support for reflection.

[1] Do not be confused over the use of the term 'attribute'. In OO terminology (and also commonly in Java) the terms 'attribute', 'field', and 'property' are often used interchangeably to mean a class's field. In C#, 'fields' and 'properties' refer to different class members, and 'attributes' are special constructs used to tag (or label) classes, interfaces, or class members .

[2] If you have ever done any COM+ programming before, you might have used a less refined form of attributes too. COM attributes, like 'transaction_required' or 'queueable', are added to a COM component's IDL to provide transaction support or MSMQ functionality. In .NET, attributes are coded within the source code itself, instead of in a separate IDL file.

[3] The nearest Java feature to C# attributes is marker interfaces. Marker interfaces are interfaces which do not contain any members, and are only used during runtime to determine if a particular object is of this interface type. The most famous marker interfaces in Java are probably java.lang.Serializable and java.lang.Cloneable . However, as you will see, comparing marker interfaces with C# attributes is like comparing a Californian Redwood with a bean sprout.

You can also think of an attribute as a language construct that decorates a class entity [4] with additional information which can be used by the CLR (standard attributes) or your own codes (custom attributes).

[4] I use the term 'class entity' in this chapter (and the next ) to refer to classes, methods , interfaces, method parameters, fields, properties, indexes, delegates, events, and method parameters which can be marked by an attribute. The ' marked ' entity is known as the attribute target.

Attributes is not an easy topic to understand, and writing custom attributes can be very complex. I shall start by looking at an example, and then move on to explain what is happening. After giving you a general grasp of the idea, I shall then discuss several standard predefined attributes you can use. Writing your own custom attributes will be covered in the next chapter.



From Java to C#. A Developers Guide
From Java to C#: A Developers Guide
ISBN: 0321136225
EAN: 2147483647
Year: 2003
Pages: 221
Authors: Heng Ngee Mok

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net