Attributes in C# Tutorial | Learn to work with attributes in C#
C Attributes Tutorial ACTE

Attributes in C# Tutorial | Learn to work with attributes in C#

Last updated on 28th Jan 2022, Blog, Tutorials

About author

Jagan Mohan (Senior C# Developer )

Jagan Mohan is a Senior Senior C# Developer and has extensive knowledge in the following areas: WPF, XML, REST, Agile, V Model, C#, SQL Server, Web API, ASP, and.NET.

(5.0) | 17982 Ratings 1758
    • Introduction to HTML Attribute
    • Attribute specification
    • Representing and Utilizing Custom Attribute Classes in C#
    • Conditional
    • How Accomplishes .NET Use Attributes in the Common Language Runtime?
    • Custom Attributes versus Class Properties
    • Creating custom attributes
    • The following code shows the DeBugInfo class
    • Creating a Custom Attribute Class
    • Applying the Custom Attribute
    • Applying the Custom Attribute
    • Conclusion

    Subscribe For Free Demo


      Introduction to HTML Attribute

      Attributes are declarative tags used to convey information about the behavior of various elements in your program, such as classes, methods, structures, enumerators, and assemblies, to the runtime. You can use attributes to add declarative information to your program. Declarative tags are represented by square brackets ([]) placed above the elements used. The attribute is used to add metadata such as compiler instructions and other information such as comments, descriptions, methods, and classes to the program. The .Net Framework provides two types of attributes: predefined attributes and user-defined attributes.

      Attribute specification

      The syntax for specifying an attribute is: –

      • [attribute (positional_parameters, name_parameter = value, …)]
      • element

      The name of the attribute and its value are enclosed in square brackets before the element to which the attribute applies. Positional parameters specify important information, and name parameters specify optional information.

    • Predefined attributes
    • The .Net Framework provides three predefined attributes (AttributeUsage)
    • Conditional
    • Abolition

    • Attribute Usage

      The predefined AttributeUsage attribute describes how to use the custom attribute class. Specifies the type of element to which the attribute can be applied. The syntax for specifying this attribute is:

      Here, the validon parameter specifies the language element in which the attribute can be placed. This is a combination of values ​​in the AttributeTargets enumerator.

    • The default is AttributeTargets.All. The allowmultiple parameter (optional) provides the value for the AllowMultiple property of this attribute. This is a Boolean value. If true, the attribute is reusable.

    • The default is false (disposable). The inherited parameter (optional) provides a Boolean value that is the value of the inherited property of this attribute. If true, the derived class inherits the attribute. The default is false (not inherited).

      • [AttributeUsage (
      • AttributeTargets.Class |
      • AttributeTargets.Constructor |
      • AttributeTargets.Field |
      • AttributeTargets.Method |
      • AttributeTargets.Property,
      • AllowMultiple = true)]

      Representing and Utilizing Custom Attribute Classes in C#

    • The intricate, part style improvement that organizations expect out of present-day programming engineers requires more prominent plan adaptability than the plan systems of the past.

    • Microsoft’s .NET Framework utilizes traits to give added usefulness through what is known as “revelatory” programming. Ascribes improved adaptability in programming frameworks since they advance free coupling of usefulness. Since you can make your custom property classes and afterward follow up on them, you can use the free coupling force of traits for your motivations.

    • The .NET Framework makes numerous parts of Windows programming a lot easier. By and large, the Framework’s utilization of metadata that .NET compilers tie to congregations at an aggregate time makes precarious programming more straightforward. To be sure, the utilization of inborn metadata makes it workable for .NET to calm us from “DLL Hell.”

    • Course Curriculum

      Learn C and C Plus Plus Certification Training Course to Build Your Skills

      Weekday / Weekend BatchesSee Batch Details


      This predefined attribute marks a conditional method whose execution depends on a specified preprocessing identifier. It causes conditional compilation of method calls, depending on the specified value such as Debug or Trace. For example, it displays the values of the variables while debugging a code.

      Syntax for specifying this attribute is as follows −

      • [Conditional(
      • conditionalSymbol
      • )]
      • For example,
      • [Conditional(“DEBUG”)]

      The following example demonstrates the attribute −

      • #define DEBUG
      • using System;
      • using System.Diagnostics;
      • public class Myclass {
      • [Conditional(“DEBUG”)]
      • public static void Message(string msg) {
      • Console.WriteLine(msg);
      • }
      • }
      • class Test {
      • static void function1() {
      • Myclass.Message(“In Function 1.”);
      • function2();
      • }
      • static void function2() {
      • Myclass.Message(“In Function 2.”);
      • }
      • public static void Main() {
      • Myclass.Message(“In Main function.”);
      • function1();
      • Console.ReadKey();
      • }
      • }

      When the above code is compiled and executed, it produces the following result −

    • In Main function
    • In Function 1
    • In Function 2

    • This predefined attribute marks a program entity that should not be used. This allows you to instruct the compiler to discard a particular target element. For example, if a new method is used in a class and you want to keep the old method in the class, you can deprecate it by displaying a message to use the new method instead of the old method.

      The syntax for specifying this attribute is:-

      • [Obsolete (
      • message)
      • )]
      • [Abolished (message, is an error)
      • )]]

      The parameter message here is a string that explains why the item was deprecated and what to use instead. The iserror parameter is a Boolean value. If its value is true, the compiler should treat the use of the element as an error. The default is false (the compiler will generate a warning). The following program demonstrates this using the system.

      • public class MyClass {
      • [Obsolete (“Do not use OldMethod, use NewMethod instead”, true)]
      • static void OldMethod () {
      • Console.WriteLine (“Old method”);
      • }
      • static void NewMethod () {
      • Console.WriteLine (“This is a new method”);
      • }
      • public static void Main () {
      • OldMethod ();
      • }
      • }

      When you try to compile a program, the compiler throws an error message similar to the following:

      Do not use OldMethod, use NewMethod instead.

      Create a custom attribute

      The .Net Framework allows you to create custom attributes that can be used to store declarative information and retrieve it at run time. This information can be associated with each target element based on design criteria and application needs. Creating and using custom attributes involves four steps-

    • Declaring custom attributes
    • Creating custom attributes
    • Apply custom attributes to target program elements

    • Access to attributes by reflection

      The final step is to write a simple program to analyze the metadata and find the various notations. Metadata is information about the data, or information used to describe other data. This program must use reflection to access the attributes at run time. This will be explained in the next chapter.

      Custom attribute declaration

      The new custom attribute must be derived from the System.Attribute class. Example:

      • // Custom attribute BugFix assigned to a class and its members
      • [AttributeUsage (
      • AttributeTargets.Class |
      • AttributeTargets.Constructor |
      • AttributeTargets.Field |
      • AttributeTargets.Method |
      • AttributeTargets.Property,
      • AllowMultiple = true)]
      • public class DeBugInfo: System.Attribute
      • In the previous code, we declared a custom attribute called DeBugInfo.

      How Accomplishes .NET Use Attributes in the Common Language Runtime?

      Before you begin to consider what you can achieve with your custom property classes, how about we inspect a portion of the standard credits that the Common Language Runtime as of now makes accessible. Does the [WebService] property give a basic example?it allows you to transform any open strategy for a WebService subclass into a technique that you can uncover as a component of the Web Service simply by appending the [WebMethod] quality to the technical definition.

      • public class SomeWebService :
      • System.Web.Services.WebService
      • {
      • [WebMethod]
      • public DataSet GetDailySales( )
      • {
      • / code to deal with the solicitation…
      • }
      • }

      You essentially connect the [WebMethod] characteristic to the strategy and .NET handles all the other things for you in the background. Utilizing the [Conditional] quality permits you to make a given strategy contingent in light of the presence or non-appearance of the predetermined preprocessing image. For instance, the accompanying code:

      • public class SomeClass
      • {
      • [Restrictive( “Investigate” )]
      • public void UnitTest( )
      • {
      • // code to do unit testing…
      • }
      • }

      Custom Attributes versus Class Properties

    • Clear similitudes exist among characteristics and customary part properties of a class. This can make it hard to conclude when and where you should use a custom quality class. Designers generally allude to properties of a class and their qualities as being “credits” themselves, so what truly is the contrast among properties and traits?

    • A characteristic takes something very similar to “shape and structure” as a property when you characterize it, yet you can connect it to all ways of various get-together level types? not simply Classes. Table 2 records every one of the gathering levels sorts that you can apply characteristics to.

    • Part properties of a class are additionally restricted in one more manner by which credits are not. By definition, a part property is attached to a particular class. That part property can at any point be utilized through an example or subclass occasion of the class on which the property was characterized.

    • Then again, you can join/apply ascribes anyplace! The main prerequisite is that the get-together sort the property is being connected to matches the validation definition in the custom characteristic. I’ll speak more about the validation property of custom characteristic classes in the following segment. This trait of properties assists with advancing the free coupling that is so useful in part style advancement.

    • One more distinction among properties and characteristics connects with the qualities you can store in every one of them. The upsides of part properties are occasion esteems and can be changed at run-time.

    • In any case, on account of traits, you set qualities at configuration time (in source code) and afterward incorporate the characteristics (and their qualities) straightforwardly into the metadata contained in a get-together. After that point, you can’t change the upsides of the attributes? you’ve transformed the upsides of the traits into hard-coded, genuine just information.

    • Consider this when you connect a trait. On the off chance that you connect a characteristic to a class definition, for instance, each occasion of the class will have similar qualities allocated to the property paying little heed to the number of objects of this class type you launch. You can’t join a characteristic to an occurrence of a class. You may just join a characteristic to a Type/Class definition.

    • Creating custom attributes

      Let’s create a custom attribute called DeBugInfo that stores the information obtained by debugging the program. Save the following information-

    • Error code number
    • The name of the developer who identified the bug
    • The date the code was last checked
    • String message to save developer annotations
    • The DeBugInfo class has three private properties to store the first three pieces of information and one public property to store the message. Therefore, the bug number, developer name, and review date are positional parameters of the DeBugInfo class, and the message is an optional or named parameter.
    • Each attribute requires at least one constructor.
    • Positional parameters must be passed via the constructor.

    • The following code shows the DeBugInfo class-

      • // custom attribute BugFix assigned to a class and its members.
      • [AttributeUsage (
      • AttributeTargets.Class |
      • AttributeTargets.Constructor |
      • AttributeTargets.Field |
      • AttributeTargets.Method |
      • AttributeTargets.Property,
      • AllowMultiple = true)]
      • public class DeBugInfo: System.Attribute {
      • private int bugNo;
      • Private String developer.
      • Private string lastReview;
      • Public string message.
      • public DeBugInfo (int bg, string dev, string d) {
      • this.bugNo = bg;
      • this.developer = dev;
      • this.lastReview = d;
      • }
      • public int BugNo {
      • get {
      • return bugNo;
      • }
      • }
      • Public String Developer {
      • get {
      • return Developer;
      • }
      • }
      • public string LastReview {
      • get {
      • return lastReview;
      • }
      • }
      • Public String Message {
      • get {
      • Feedback;
      • }
      • set {
      • message = value;
      • }
      • }
      • }

      Course Curriculum

      Get JOB Oriented C and C Plus Plus Training for Beginners By MNC Experts

      • Instructor-led Sessions
      • Real-life Case Studies
      • Assignments
      Explore Curriculum

      Creating a Custom Attribute Class

      Presently we’ll make a more practical execution of the thoughts introduced previously. How about we make a custom trait class. This will permit us to store a few following data about code changes that you would ordinarily record as remarks in the source code. For the model, we’ll record only a couple of things: deformity id, engineer id, the date of the change, the beginning of the imperfection, and a remark about the fix. To keep the model straightforward we’ll zero in on making a custom characteristic class (DefectTrackAttribute) assigned for utilizing just with classes and techniques. On the off chance that you haven’t utilized traits previously, the accompanying line of code may look a piece bizarre.

      • [AttributeUsage(
      • AttributeTargets.Class |
      • AttributeTargets.Method,
      • AllowMultiple = true)]

      This line connects a [AttributeUsage] trait to the property class definition. Square section grammar recognizes the development as a quality. In this way, Attributes classes can have their traits.

      Applying the Custom Attribute

    • You’ve as of now seen that you can connect a characteristic to an objective thing in your C# code by placing the quality name and its boundaries in square sections preceding the thing’s revelation articulation.
    • In Listing 2 you join the [DefectTrack] quality to a few techniques and a few classes.
    • You want to guarantee that you approach the class definition for your custom characteristic so you start by including this line.

      • utilizing MyAttributeClasses ;

      Past that you’re not kidding or “adorning” your class statements and a portion of your strategies with the [DefectTrack] custom property.

      Applying the Custom Attribute

      A custom property affirmation starts with the System. AttributeUsageAttribute, which characterizes a portion of the critical qualities of your trait class. For instance, you can indicate whether your quality can be acquired by different classes or determine which components the characteristic can be applied to. The attribute is applied by placing it immediately before its target −

      • [DeBugInfo(45, “Zara Ali”, “12/8/2012”, Message = “Return type mismatch”)]
      • [DeBugInfo(49, “Nuha Ali”, “10/10/2012”, Message = “Unused variable”)]
      • class Rectangle {
      • //member variables
      • protected double length;
      • protected double width;
      • public Rectangle(double l, double w) {
      • length = l;
      • width = w;
      • }
      • [DeBugInfo(55, “Zara Ali”, “19/10/2012”, Message = “Return type mismatch”)]
      • public double GetArea() {
      • return length * width;
      • }
      • [DeBugInfo(56, “Zara Ali”, “19/10/2012”)]
      • public void Display() {
      • Console.WriteLine(“Length: {0}”, length);
      • Console.WriteLine(“Width: {0}”, width);
      • Console.WriteLine(“Area: {0}”, GetArea());
      • }
      • }

      C and C Plus Plus Sample Resumes! Download & Edit, Get Noticed by Top Employers! Download


      Attribute give a strong strategy for partner metadata, or definitive data, with code (gatherings, types, techniques, properties, etc). After a property is related with a program element, the quality can be questioned at show time to utilizing a method called reflection.

    Are you looking training with Right Jobs?

    Contact Us
    Get Training Quote for Free