C # & Dot NET Framework Unit-V


• Attributes are a mechanism for adding metadata, such as compiler instructions and other data about your data, methods, and classes, to the program itself. • Attributes are inserted into the metadata and are visible through ILDasm and other metadata-reading tools.

• Reflection is the process by which a program can read its own metadata. • A program is said to reflect on itself, extracting metadata from its assembly and using that metadata either to inform the user or to modify its own behavior.

• For example. • The element to which you attach an attribute is referred to as the target of that attribute.Example for Attribute • An attribute is an object that represents data you want to associate with an element in your program. . the attribute: [NoIDispatch] • is associated with a class or an interface to indicate that the target class should derive from IUnknown rather than IDispatch when exporting to COM.

.key")] • This inserts metadata into the assembly to designate the program's StrongName.Example • [assembly: AssemblyKeyFile("c:\\myStrongName.

Types of Attributes • Attributes come in two flavors: – intrinsic and – custom . • Intrinsic attributes are supplied as part of the Common Language Runtime (CLR). and they are integrated into . .NET. • Custom attributes are attributes you create for your own purposes.

others to a class or interface. such as [WebMethod]. These are called the attribute targets. and some. are applied to class members. .Attribute Targets • Some attributes are applied to an assembly.

module. class. interface. enum. property. constructor. parameter. event. or struct Applied to the assembly itself Applied to instances of the class Applied to a given constructor Applied to the delegated method Applied to an enumeration Applied to an event Applied to a field Interface Method Module Parameter Property ReturnValue Struct Applied to an interface Applied to a method Applied to a single module Applied to a parameter of a method Applied to a property (both get and set.Possible attribute targets Table 18-1. return value. if implemented) Applied to a return value Applied to a struct . delegate. method. field. Possible attribute targets Member name All Assembly Class Constructor Delegate Enum Event Field Usage Applied to any of the following elements: assembly.

\\keyFile.snk")] • This can also be done by separating the attributes with commas: • [assembly: AssemblyDelaySign(false). You can combine attributes by stacking one on top of another: • [assembly: AssemblyDelaySign(false)] [assembly: AssemblyKeyFile(".Applying Attributes • Apply attributes to their targets by placing them in square brackets immediately before the target item. • assembly: AssemblyKeyFile(".snk")] .\\keyFile.

• The principal intrinsic attributes are those used for COM.Applying Attributes • The System. and for version attributes. including attributes for assemblies (such as the keyname attribute).Runtime namespace offers a number of intrinsic attributes. . those used to modify the Interface Definition Language (IDL) file from within a source-code file. • You can organize the intrinsic attributes by how they are used. and those used by the Visual C++ compiler. for configuration (such as debug to indicate the debug build). those used by the ATL Server classes.

. the class declaration.Applying Attributes • • • • [Serializable] attribute to the class: [Serializable] class MySerializableClass The attribute tag is put in square brackets immediately before its target -.in this case.

"Jesse Liberty". • This would make it easy to see in our source code. • The attribute would serve the purposes of a comment. our development organization wants to keep track of bug fixes. Comment="Off by one error")] • we should write a program to read through the metadata to find these bug-fix notations and update the database. • we might add comments to your code along the lines of: – // Bug 323 fixed by Jesse Liberty 1/1/2005. but there is no enforced connection to Bug 323 in the database.Custom Attributes • For example. • A custom attribute might be just what we need."1/1/2005". but we like to tie your bug reports to specific fixes in the code. we should replace our comment with something like this: • [BugFixAttribute(323. we already keep a database of all your bugs. but would also allow us to retrieve the information programmatically through tools we create. .

Attribute • You need to tell the compiler which kinds of elements this attribute can be used with (the attribute target).Declaring an Attribute • To create a custom attribute.Attribute: • public class BugFixAttribute : System. Specify this with an attribute . derive your new custom attribute class from System.

Method | AttributeTargets.AttributeUsage • [AttributeUsage(AttributeTargets.Property. AllowMultiple = true)] .Constructor | AttributeTargets.Field | AttributeTargets.Class | AttributeTargets.

AttributeUsage • AttributeUsage is an attribute applied to attributes: a meta-attribute. fields. – In this example.in this case. . data about the metadata. It provides. indicating that class members can have more than one BugFixAttribute assigned. if you will. you pass two arguments. AllowMultiple is set to true. – The second argument is a flag that indicates whether a given element might receive more than one such attribute. – The first argument is a set of flags that indicate the target -. and properties. methods. meta-metadata -that is. the class and its constructor. • For the AttributeUsage attribute constructor.

"Jesse Liberty". Thus. • The convention is to append the word Attribute to your attribute name. Comment="Off by one")] • The compiler will first look for an attribute named BugFix and. will then look for BugFixAttribute.Naming an Attribute • The new custom attribute in this example is named BugFixAttribute. "01/01/05". you can write: • [BugFix(123. • The compiler supports this by allowing you to call the attribute with the shorter version of the name. if it does not find that. .

• Attributes take two types of parameters: positional and named. • In the BugFix example. and comment is a named parameter. the programmer's name and the date are positional parameters.Constructing an Attribute • Every attribute must have at least one constructor. • Named parameters are implemented as properties .

bugID = bugID.programmer = programmer. • } .positional parameters • public BugFixAttribute(int bugID.date = date. this. string programmer. string date) • { • this. this.

Named parameters • public string Comment { get { return comment. } } . } set {comment = value.

positional parameters • It is common to create read-only properties for the positional parameters • public int BugID { get { return bugID. } } .

the following program creates a simple class named MyMath and gives it two functions. . you can put it to work by placing it immediately before its target. • Comment="Fixed off by one errors")] • public class MyMath • These attributes will be stored with the metadata. • Assign BugFixAttributes to the class to record its codemaintenance history: • [BugFixAttribute(121."01/03/05")] [BugFixAttribute(107.Using an Attribute • Once you have defined an attribute."Jesse Liberty"."01/04/05". • To test the BugFixAttribute of the preceding example."Jesse Liberty".

Property.Method | AttributeTargets.Working with custom attributes • namespace Programming_CSharp { using System.Field | AttributeTargets. // create custom attribute to be assigned to class members [AttributeUsage(AttributeTargets. using System.Reflection.Class | AttributeTargets. AllowMultiple = true)] .Constructor | AttributeTargets.

• public class BugFixAttribute : System.bugID = bugID. this.programmer = programmer. this.Attribute { // attribute constructor for positional parameters public BugFixAttribute(int bugID. } . string programmer. string date) { this.date = date.

// accessor public int BugID { get { return bugID. } } .

} } . } set { comment = value.• // property for named parameter public string Comment { get { return comment.

private string date. private string comment.// accessor public string Date { get { } // accessor public string Programmer { get { } // private member data private int bugID. } . private string programmer. • } return date. } return programmer.

• • // ********* assign the attributes to the class ******** [BugFixAttribute(121."Jesse Liberty". } public double DoFunc2(double param1) { return param1 / 3. } } ."Jesse Liberty". Comment="Fixed off by one errors")] public class MyMath { public double DoFunc1(double param1) { return param1 + DoFunc2(param1)."01/03/05")] [BugFixAttribute(107."01/04/05".

Console. } } } • Output: Calling DoFunc(7). Result: {0}". Result: 9.3333333333333333 . mm.WriteLine("Calling DoFunc(7).DoFunc1(7)).• public class Tester { public static void Main( ) { MyMath mm = new MyMath( ).

• the attributes had absolutely no impact on the output. • A quick look at the metadata using ILDasm does reveal that the attributes are in place. for the moment. In fact. . you have only my word that the attributes exist at all.

The metadata in the assembly .