attributes.md - brainchildservices/curriculum GitHub Wiki
Slide 1
Attributes
Attributes are like adjectives, which are used for metadata annotation that can be applied to a given type, assembly, module, method and so on. The .NET framework stipulates two types of attribute implementations, which are Predefined Attributes and Custom Attributes.
Attributes are types derived from the System.Attribute
class. This is an abstract class defining the required services of any attribute. The following is the syntax of an attribute;
[type: attributeName(parameter1, parameter2,.........n)]
Slide 2
The attribute name is the class name of the attribute. Attributes can have zero or more parameters. The following code sample states the attributes implementation in which we are declaring a method as deprecated using the obsolete attribute:
using System;
namespace attributes
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Attributes sample");
TestMethod();
Console.ReadKey();
}
[Obsolete("Deprecated Method",false)]
public static void TestMethod()
{
Console.WriteLine("Hello world");
}
}
}
Slide 3
The following figure shows the MSIL code of the TestMethod method as displayed in ILDASM. Notice the custom directive that defines the Obsolete attribute.
Slide 4
Attributes might be useful for documentation purposes. They fulfill many roles, including describing serialization, indicating conditional compilation, specifying import linkage and setting class blueprint and so on. Attributes allow information to be defined and applied to nearly any metadata table entry. This extensible metadata information can be queried at run time to dynamically alter the way code executes.
The C# compiler itself has been programmed to discover the presence of numerous attributes during the compilation process. For example, if the csc.exe compiler discovers an item being annotated with the [obsolete] attribute, it will display a compiler warning in the IDE error list.
Ref:- https://www.c-sharpcorner.com/UploadFile/84c85b/using-attributes-with-C-Sharp-net/