EDUCBA

EDUCBA

MENUMENU
  • Free Tutorials
  • Free Courses
  • Certification Courses
  • 600+ Courses All in One Bundle
  • Login

C# Custom Attribute

By Priya PedamkarPriya Pedamkar

Home » Software Development » Software Development Tutorials » C# Tutorial » C# Custom Attribute

C# Custom Attribute

Introduction to C# Custom Attribute

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:

Start Your Free Software Development Course

Web development, programming languages, Software testing & others

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)

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)

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.

Popular Course in this category
C# Training Program (6 Courses, 17 Projects)6 Online Courses | 17 Hands-on Project | 89+ Hours | Verifiable Certificate of Completion | Lifetime Access
4.6 (8,847 ratings)
Course Price

View Course

Related Courses
ASP.NET Training (8 Courses, 19 Projects).NET Training Program (4 Courses, 19 Projects)

Syntax:

AttributeUsage(AttributeTargets.Method, AllowMultiple = true)

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
}

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;
}

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;}
}

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));
}
}

Output:

C# Custom Attribute - 1

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());
}
}

Output:

C# Custom Attribute - 2

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();
}
}

Output:

Main method

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).

Recommended Articles

This is a guide to C# Custom Attribute. Here we discuss an introduction to C# Custom Attribute with Steps for creating the attribute and respective examples. You can also go through our other related articles to learn more –

  1. Deserialization in C#
  2. C# Serialization
  3. C# Out Parameter
  4. C# Interface

All in One Software Development Bundle (600+ Courses, 50+ projects)

600+ Online Courses

50+ projects

3000+ Hours

Verifiable Certificates

Lifetime Access

Learn More

0 Shares
Share
Tweet
Share
Primary Sidebar
C sharp Tutorial
  • Basic
    • Uses Of C#
    • C# Versions
    • C# Data Types
    • Variables in C#
    • Namespaces in C#
    • C# Compilers
    • C# Keywords
    • Iterators in C#
    • Objects in C#
    • C# Object Dispose
    • C# object to XML
    • C# check object type
    • C# Object Serialization
    • Pointers in C#
    • C# Literals
    • C# Commands
    • C# Custom Attribute
    • Type Casting in C#
    • String vs String C#
    • C# Struct vs Class
  • Operators
    • Logical Operators in C#
    • Conditional Operators in C#
    • Bitwise Operators in C#
    • C# OR Operator
    • C# Ternary Operators
    • Operator Precedence in C#
  • Control Statement
    • C# if Statement
    • Else If in C#
    • Continue in C#
    • Break in C#
    • Switch Statement in C#
    • Goto Statement in C#
  • Loops
    • C# For Loop
    • C# While Loop
    • C# do-while loop
    • C# foreach Loop
  • Arrays
    • Arrays in C#
    • 2D Arrays in C#
    • C# Jagged Arrays
    • String Array in C#
    • C# Multidimensional Arrays
  • Constructor and Destructor
    • Constructor in C#
    • Copy Constructor in C#
    • Static Constructor in C#
    • Destructor in C#
  • overloading and overrideing
    • Overloading and Overriding in C#
    • Overloading in C#
    • Overriding in C#
    • Method Overloading in C#
    • Method Overriding in C#
    • Operator Overloading in C#
  • Functions
    • C# Functions
    • C# String Functions
    • Math Functions in C#
    • Recursive Function in C#
    • C# Anonymous Functions
    • C# Local Functions
    • Enum in C#
    • Trim() in C#
    • clone() in C#
    • C# random
    • C# String Format()
    • C# String Interpolation
    • C# StartsWith()
    • C# String IndexOf()
    • DateTime in C#
    • C# Nullable
    • C# nameof
    • C# checked
    • C# String PadLeft
    • Convert String to Double in C#
    • Convert int to String C#
    • String to Date C#
    • C# intern()
    • C# Stopwatch
    • C# DirectoryInfo
    • C# Compare()
    • C# Base
    • C# SOAP
    • Lock in C#
  • Advanced
    • Inheritance in C#
    • Exception Handling in C#
    • Types of Exception in C#
    • C# FileNotFoundException
    • C# NullReferenceException
    • C# OutOfMemoryException
    • C# StackOverflowException
    • Custom Exception in C#
    • What is Multithreading in C#
    • C# finally
    • C# System.IO
    • What is StringBuilder in C#
    • DataReader C#
    • BinaryWriter in C#
    • C# BinaryReader
    • TextWriter in C#
    • TextReader in C#
    • C# StringReader
    • C# StringWriter
    • C# StreamReader
    • C# StreamWriter
    • C# FileInfo
    • What is Design Pattern in C#?
    • Multithreading in C#
    • Sorting in C#
    • Bubble Sort in C#
    • C# SortedList
    • C# SortedSet
    • C# SortedDictionary
    • Abstract Class in C#
    • Access Modifiers in C#
    • C# Generics
    • Deserialization in C#
    • C# Thread
    • C# Thread Join
    • C# Thread Sleep
    • C# Thread Synchronization
    • C# Class
    • Sealed in C#
    • Sealed Class in C#
    • Polymorphism in C#
    • C# Call By Reference
    • Virtual Keyword in C# 
    • Yield Keyword in C#
    • Regular Expression in C#
    • C# Lambda Expression
    • C# Predicate
    • Convert Object to JSON C#
    • Checkbox in C#
    • C# MessageBox
    • Collections in C#
    • List in C#
    • C# LinkedList
    • Listbox in C#
    • Protected in C#
    • C# EventHandler
    • Private in C#
    • this Keyword in C#
    • Static Keyword in C#
    • C# Out Parameter
    • Assert in C#
    • C# Delegates
    • C# Interface
    • Generics in C#
    • Timer in C#
    • C# Serialization
    • Metadata in C#
    • C# Stack
    • C# Using Static
    • Queue in C#
    • C# File.Exists
    • C# Tuples
    • C# Create JSON Object
    • Partial in C#
    • C# readonly
    • C# Action Delegate
    • C# Await Async
    • C# Dictionary
    • IEnumerable C#
    • C# Data Grid View
    • C# Dynamic
    • Web Services in C#
    • C# Pattern Matching
    • C# Extension Methods
    • C# XmlSerializer
  • Programs
    • Patterns in C#
    • Swapping in C#
    • Palindrome in C#
    • Factorial in C#
    • Fibonacci Series in C#
    • Random Number Generator in C#
    • Prime Numbers in C#
    • Armstrong Number in C#
    • Reverse String in C#
  • Interview questions
    • C# Interview Questions and Answers
    • C# OOP Interview Questions
    • C# Design Pattern Interview Questions

Related Courses

C# Certification Training

ASP.NET Course

.NET Course

Footer
About Us
  • Blog
  • Who is EDUCBA?
  • Sign Up
  • Corporate Training
  • Certificate from Top Institutions
  • Contact Us
  • Verifiable Certificate
  • Reviews
  • Terms and Conditions
  • Privacy Policy
  •  
Apps
  • iPhone & iPad
  • Android
Resources
  • Free Courses
  • Java Tutorials
  • Python Tutorials
  • All Tutorials
Certification Courses
  • All Courses
  • Software Development Course - All in One Bundle
  • Become a Python Developer
  • Java Course
  • Become a Selenium Automation Tester
  • Become an IoT Developer
  • ASP.NET Course
  • VB.NET Course
  • PHP Course

© 2020 - EDUCBA. ALL RIGHTS RESERVED. THE CERTIFICATION NAMES ARE THE TRADEMARKS OF THEIR RESPECTIVE OWNERS.

EDUCBA Login

Forgot Password?

EDUCBA
Free Software Development Course

Web development, programming languages, Software testing & others

*Please provide your correct email id. Login details for this Free course will be emailed to you
Book Your One Instructor : One Learner Free Class

Let’s Get Started

This website or its third-party tools use cookies, which are necessary to its functioning and required to achieve the purposes illustrated in the cookie policy. By closing this banner, scrolling this page, clicking a link or continuing to browse otherwise, you agree to our Privacy Policy

EDUCBA

*Please provide your correct email id. Login details for this Free course will be emailed to you
EDUCBA
Free Software Development Course

Web development, programming languages, Software testing & others

*Please provide your correct email id. Login details for this Free course will be emailed to you

Special Offer - C# Certification Training Learn More