C# Custom Attribute

王林
Release: 2024-09-03 15:07:19
Original
958 people have browsed it

While we get into what is a custom attribute we must understand attributes. Attributes are metadata extensions that will give additional information to the C# compiler about elements in the C# program at the runtime. These attributes are used to put conditions or increase the readability and efficiency of the code. There are so many predefined attributes that exist in C# (C sharp), and also we have the facility to create new user attributes called “custom attributes”. To create the custom class, we must construct the classes from the System. Attribute class.

How does Custom Attribute work in C#?

C# custom attribute is working based on predefined classes used to construct. We will look into how to create the custom attributes step by step. Steps for creating the custom attribute:

Step #1

By using the AttributeUsageAttribute tag: AttributeUsageAttribute tag used to construct the attribute. This tag is also used for what are the target attributes are and if this can be inherited or if multiple objects or instances of the attribute can exist. This AttributeUsageAttribute tag has 3 primary members

  • AttributeUsageAttribute( AttributeTargets.All)
  • AttributeUsage(AttributeTargets.All, Inherited = false)
  • AttributeUsage(AttributeTargets.Method, AllowMultiple = true)

1. AttributeUsageAttribute(AttributeTargets.All): AttributeTargets.All is specifying that the attribute can be applied to all other parts of the program whereas Attribute. The class will indicate that it should apply to the class and AttributeTargets.Method parameter to the custom method.

Syntax:

AttributeUsageAttribute( AttributeTargets.All)
Copy after login

2. AttributeUsage(AttributeTargets.All, Inherited = false): From this AttributeUsageAttribute( AttributeTargets.All) is an inherited member and it is indicative of the custom attribute may be inherited or not. Inherited = false is a boolean value either true/false. If we did not specify the Inherited = true/false then the default value is true.

Syntax:

AttributeUsage(AttributeTargets.All, Inherited = false)
Copy after login

3. AttributeUsage(AttributeTargets.Method, AllowMultiple = true): From this AllowMultiple parameter tells us if there is more than one object of the attribute exists or not. It also takes the boolean value as well. By default this boolean value is false.

Syntax:

AttributeUsage(AttributeTargets.Method, AllowMultiple = true)
Copy after login

Step #2

1. By defining attribute class: This more or similar to the normal class definition. The class name is conventional ends in Attribute. This attribute class inherited from System. Attribute class.

Syntax:

[AttributeUsage(AttributeTargets.All, Inherited = true, AllowMultiple = false)]
public class MyAttributeDefinition: Attribute
{
//some logic or methods
}
Copy after login

Step #3

1. Defining Properties and Constructors: Defining constructor similar to all other classes constructors for setting the default values and Properties are used to define database connection name information, static information, etc.

Syntax #1

public MyAttribute(dataType dataTypeValue)
{
this.dataTypeValue= dataTypeValue;
}
Copy after login
Note: Custom attributes have properties to get and set the data type variables.

Syntax #2

public dataType Properties
{
get {return this.dataTypeValue;}
set {this.value = presentValue;}
}
Copy after login

Examples to Implement C# Custom Attribute

Below are the examples mentioned:

Example #1

Custom Attribute with typeOf operator

Code:

// including packages
using System;
using System.Reflection;
using System.Collections.Generic;
// Creating a custom class from Attribute class
class CustomAttribute : Attribute {
// private variables declaration
private string name;
private string company;
//parameterized class CustomAttribute constuctor
public CustomAttribute(string name, string company)
{
this.name = name;
this.company = company;
}
// method to display the fields by using reflection class
public static void AttributeDisplay(Type classType)
{
Console.WriteLine("All the Methods of the class {0} are", classType.Name);
//methods of the class for store all the attribute values
MethodInfo[] methods = classType.GetMethods();
//looping through method attribute values by using for loop
for (int i = 0; i < methods.GetLength(0); i++) {
//create the array to recieve all the custom attribute values
object[] attributesArray = methods[i].GetCustomAttributes(true);
// foreach loop to read the values through all attributes of the method
foreach(Attribute item in attributesArray)
{
if (item is CustomAttribute) {
//display the custom attribute values
CustomAttribute attributeObject = (CustomAttribute)item;
Console.WriteLine("{0} - {1}, {2} ", methods[i].Name,
attributeObject.name, attributeObject.company);
}
}
}
}
}
//Employer class to create employer fields
class Employer {
//employer fields declaration
int employeeID;
string name;
//Parameterized Employer class constructor
public Employer(int eID, string name)
{
this.employeeID = eID;
this.name = name;
}
// Applying the custom attribute for CustomAttribute for the  getId method
[CustomAttribute("Accessor Values", "Generates employee ID")] public int getEmployeeID()
{
return employeeID;
}
// Applying the custom attribute to CustomAttribute for the getName method
[CustomAttribute("Accessor Values", "Generates employee ID")] public string getName()
{
return name;
}
}
//create employee class
class Employee {
//Declaring variables of Employee
int employeeID;
string name;
//Parameterized Employee constructor
public Employee(int eID, string name)
{
this.employeeID = eID;
this.name = name;
}
// Applying the custom attribute CustomAttribute for the getEmployeeID method
[CustomAttribute("Accessor Values", "Generates employee ID")] public int getEmployeeID()
{
return employeeID;
}
// Applying the custom attribute CustomAttribute for the getName method
[CustomAttribute("Accessor Values", "Generates employee ID")] public string getName()
{
return name;
}
}
//create a class for display the output
public class Program {
// main method for the application
public static void Main(string[] args)
{
//calling static method for display typeOf employer class
CustomAttribute.AttributeDisplay(typeof(Employer));
Console.WriteLine();
//calling static method for display typeOf employee class
CustomAttribute.AttributeDisplay(typeof(Employee));
}
}
Copy after login

Output:

C# Custom Attribute

Example #2

Custom attribute with Employee details

Code:

using System;
[AttributeUsage(AttributeTargets.All)]
class CustomAttribute : Attribute {
private string name;
private string designation;
// Constructor
public CustomAttribute(string name, string designation)
{
this.name = name;
this.designation = designation;
}
// setters and getters
public string Name
{
get { return name; }
}
// property to get designation
public string Action
{
get { return designation; }
}
}
class Employee {
private int empID;
private string empName;
private double salary;
[CustomAttribute("Modifier", "Assigns the Employee Details")]
public void setDetails(int id,string name, double sal)
{
empID = id;
empName = name;
salary=sal;
}
[CustomAttribute("It is an Accessor", "Displays empID")] public int getEmpID()
{
return empID;
}
[CustomAttribute("It is an Accessor", "Displays empID")] public string getEmpName()
{
return empName;
}
[CustomAttribute("It is an Accessor", "Displays empID")] public double getSalary()
{
return salary;
}
}
public class EmployeeDetailsOut {
// main method for run the application
//main method modifier must be public
public static void Main(string[] args)
{
Employee emp = new Employee();
emp.setDetails(2424, "Paramesh", 400000.00);
Console.WriteLine("Employee Details");
Console.WriteLine("Employee ID Number : " + emp.getEmpID());
Console.WriteLine("Employee Name : " + emp.getEmpName());
Console.WriteLine("Employee Salary : " + emp.getSalary());
Console.WriteLine("\n");
Employee emp1 = new Employee();
emp1.setDetails(2423, "Amardeep", 600000.00);
Console.WriteLine("Employee Details");
Console.WriteLine("Employee ID Number : " + emp1.getEmpID());
Console.WriteLine("Employee Name : " + emp1.getEmpName());
Console.WriteLine("Employee Salary : " + emp1.getSalary());
}
}
Copy after login

Output:

C# Custom Attribute

Example #3

Custom Attribute demonstration

Code:

using System;
using System.Diagnostics;
public class DemonstrationOfCustomAttribute {
[Conditional("DEBUG")]
public static void getMyOut(string msg) {
Console.WriteLine(msg);
}
}
public class Test {
static void firstMethod() {
DemonstrationOfCustomAttribute.getMyOut("I am first method.");
secondMethod();
}
static void secondMethod() {
DemonstrationOfCustomAttribute.getMyOut("I am second method.");
}
public static void Main() {
DemonstrationOfCustomAttribute.getMyOut("I am in main method.");
firstMethod();
}
}
Copy after login

Output:

C# Custom Attribute

Conclusion

Custom attribute in C# is used to define used declared implementation with classes. We can achieve this custom attribute implementation in 3 steps, that is by using AttributeUsageAttribute, AttributeUsage (AttributeTargets.All, Inherited = false, and AttributeUsage (AttributeTargets.Method, AllowMultiple = true).

The above is the detailed content of C# Custom Attribute. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!