Attribute is nothing more than a class that inherit from the base class Attribute.
So now what is the purpose of it?
- The base functionality in the base purpose for an attribute is to be able to assign metadata to code.
- An attribute is a declarative tag that is used to convey information to runtime about the behaviors of various elements like classes, methods, structures, enumerators, assemblies etc.
Specifying an Attribute
Syntax for specifying an attribute is as follows:
[attribute(positional_parameters, name_parameter = value, ...)] element
Name of the attribute and its values are specified within the square brackets, before the element to which the attribute is applied. Positional parameters specify the essential information and the name parameters specify the optional information.
Predefined Attributes
The .Net Framework provides three pre-defined attributes:
- AttributeUsage
- Conditional
- Obsolete
The following example demonstrates the attribute:
Here i have assigned a sample attribute named MyAttribute to the sample class Experia with a property named model and a method called Features doesn't taking any arguments.
by default we can assign sample attribute(ExpAttribute) to our property & methods.
for certain purposes to restrict it target of access or application we can decorate our attribute with another attribute with it's target that it can be applied to which called [AttributeUsage].
Let's take a look at the sample example:
AttributeTargets- by default all.
now when we decorate our sample attribute the compiler did some reflection into our attribute which show's there are two property(name & model).
let's go and assign them
In the following code, we get the current process name and load the assembly using LoadFrom method of Assembly class. Then we use GetCustomAttributes method to get all the custom attributes attached to the current assembly.
OUTPUT
Notice that there is another class there has no sample attribute applied there, which isn't showing in the result!
No comments:
Post a Comment