пятница, 26 сентября 2014 г.

Preparing to MS Exam 70-483 - create and apply attributes; read attributes;

The full set of questions I'm trying to cover in time of my preparation to MS Exam 70-483  you can find here.

Pre-defined attributes

There are 3 pre-defined classes:
  • AttributeUsage(AttributeTargets[, IsAllowMultiple[, IsInherited]]) - describes the way how a custom attribute class can be used.
  • Conditional(symbol) - check the presence or absence of the preprocessing symbol to determine execute or not particular method
  • Obsolete(message, IsError) - marks a program entity that should not be used.
  • System.Runtime.InteropServices.OptionalAttribute
AttributeUsage attribute is only valid on classes derived from System.Attribute and both AllowMultiple and Inherited are false for this attribute.

Create Attributes 

To create a custom attribute, you need to create a class that inherits from the System .Attribute abstract class:
class MyCustomAttribute : System.Attribute
You can define the scope of the attribute by applying [AttributeUsage] attribute to the created class. For this example the [MyCustomAttribute] attribute is limited to a class or a struct:
[System.AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct)]
class MyCustomAttribute : System.Attribute {

The constructor of the attribute can have only parameters of following types:

  • bool, byte, char, double, float, int, long, short, string, System.Type, object
  • a one-dimensional array of mentioned types
  • an enum type(if publicly accessible)
In contrast to positional parameters of constructor which are mandatory, named parameters are optional and represents public properties of attribute class:
[Help(field = "Some help field")]
To read attributes applied to the class, you should use reflection.

Read Attributes

An assembly has a GetCustomAttributes method that enables you to enumerate through all the custom attributes classes contained in the assembly or filter the specific type of attribute you would like to retrieve.

Assign Attributes

You need simply write attribute name in [] brackets before element you want the attribute be assigned.
To assign attribute to entire assembly, class etc. you should use attributes identifiers like this:
[assembly: Help("this a do-nothing assembly")] 
The assembly identifier before the Help attribute explicitly tells the compiler that this attribute is attached to entire assembly.
The possible identifiers are:
  • assembly 
  • module 
  • type 
  • method 
  • property 
  • event 
  • field 
  • param 
  • return