Retrieving metadata

As you are aware of OOP concepts, retrieving attribute information is as simple as creating an instance of the attribute that we want to retrieve, and then invoking the GetCustomAttribute method of the System.Attribute class.

In the following example, we define a new attribute called ChapterInfo and define a constructor to mark two of its properties as required parameters:

[System.AttributeUsage(System.AttributeTargets.Class, Inherited =false,AllowMultiple = false)]
public class ChapterInfoAttribute : Attribute
{
public string ChapterName{ get; set; }
public string ChapterAuthor { get; set; }

public ChapterInfoAttribute(string Name, string Author)
{
ChapterName = Name;
ChapterAuthor = Author;
}
}

ChapterName and ChapterAuthor are the two required parameters that the developer has to define when using this attribute.

As you can see, in the following code the attribute is being defined over the Program class with two values: Name and Author. In the main method, GetCustomAttribute is invoked to read its properties, as you would do for any other class type variable:

namespace Chapter10
{
[ChapterInfo("SAMPLECHAPTER", "AUTHOR1")]
class Program
{
static void Main(string[] args)
{
ChapterInfoAttribute _attribute = (ChapterInfoAttribute)Attribute.GetCustomAttribute(typeof(Program), typeof(ChapterInfoAttribute));
Console.WriteLine($"Chapter Name is: {_attribute.ChapterName} and Chapter Author is: {_attribute.ChapterAuthor}");
// Keep the console window open in debug mode.
System.Console.WriteLine("Press any key to exit.");
System.Console.ReadKey();
}
}
}

Observe the following output:

//Output
Chapter Name is: SAMPLECHAPTER and Chapter Author is: AUTHOR1
Press any key to exit.

As you can see, the ([ChapterInfo("SAMPLECHAPTER", "AUTHOR1")]) values passed in the attribute definition over the program class were retrieved and displayed.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.144.30.236