Attributes in C#

Attributes are used in C# to convey declarative information or metadata about various code elements such as methods, assemblies, properties, types, etc. Attributes are added to the code by using a declarative tag that is placed using square brackets ([ ]) on top of the required code element. There are two types of Attributes implementations provided by the .NET Framework are:

  1. Predefined Attributes
  2. Custom Attributes

Properties of Attributes:

  • Attributes can have arguments just like methods, properties, etc. can have arguments.
  • Attributes can have zero or more parameters.
  • Different code elements such as methods, assemblies, properties, types, etc. can have one or multiple attributes.
  • Reflection can be used to obtain the metadata of the program by accessing the attributes at run-time.
  • Attributes are generally derived from the System.Attribute Class.

1. Predefined Attributes

Predefined attributes are those attributes that are a part of the .NET Framework Class Library and are supported by the C# compiler for a specific purpose. Some of the predefined attributes that are derived from the System.Attribute base class are given as follows:

Attribute Description
AttributeUsageAttribute This attribute specifies the usage of a different attribute.
CLSCompliantAttribute This attribute shows if a particular code element complies with the Common Language Specification.
ContextStaticAttribute This attribute indicates if a static field value is unique for the specified context.
FlagsAttribute This attribute indicates if a static field value is unique for the specified context.
LoaderOptimizationAttribute This attribute sets the optimization policy for the default loader in the main method.
NonSerializedAttribute This attribute signifies that the field of the serializable class should not be serialized.
ObsoleteAttribute This attribute marks the code elements that are obsolete i.e. not in use anymore.
SerializableAttribute This attribute signifies that the field of the serializable class can be serialized.
ThreadStaticAttribute This attribute indicates that there is a unique static field value for each thread.
DllImportAttribute This attribute indicates that the method is a static entry point as shown by the unmanaged DLL.

Let’s discuss some of the predefined attributes:

CLSCompliantAttribute

This attribute shows if a particular code element complies with the Common Language Specification. If a particular code element complies with the Common Language Specification. If it doesn’t, then a warning message is issued by the compiler.

Example 1: Here, it will not give any warning message and code compiles successfully.

filter_none

edit
close

play_arrow

link
brightness_4
code

// C# program to demonstrate CLSCompliantAttribute
using System;
  
// CLSCompliantAttribute applied to entire assembly
[assembly:CLSCompliant(true)]
  
    public class GFG {
  
    // Main Method
    public static void Main(string[] args)
    {
        Console.WriteLine("GeeksForGeeks");
    }
}

chevron_right


Output:

GeeksForGeeks

Example 2: This code will give a warning message by the compiler.

filter_none

edit
close

play_arrow

link
brightness_4
code

// C# program to demonstrate CLSCompliantAttribute
// giving a warning message
using System;
  
// CLSCompliantAttribute applied to entire assembly
[assembly:CLSCompliant(true)]
  
    public class GFG {
    public uint z;
}
  
class GFG2 {
  
// Main Method
public static void Main(string[] args)
{
    Console.WriteLine("GeeksForGeeks");
}
  
}

chevron_right


Warning:

prog.cs(9,14): warning CS3003: Type of `GFG.z’ is not CLS-compliant

FlagsAttribute

The FlagsAttribute specifies that an enumeration can be used as a set of flags. This is most commonly used with bitwise operators.

Example:

filter_none

edit
close

play_arrow

link
brightness_4
code

// C# program to demonstrate FlagsAttribute
using System;
  
class GFG {
  
    // Enum defined without FlagsAttribute.
    enum Colours { Red = 1,
                   Blue = 2,
                   Pink = 4,
                   Green = 8
    }
  
    // Enum defined with FlagsAttribute.
    [Flags] enum ColoursFlags { Red = 1,
                                Blue = 2,
                                Pink = 4,
                                Green = 8
    }
  
    // Main Method
    public static void Main(string[] args)
    {
        Console.WriteLine((Colours.Red | Colours.Blue).ToString());
        Console.WriteLine((ColoursFlags.Red | ColoursFlags.Blue).ToString());
    }
}

chevron_right


Output:

3
Red, Blue

ObsoleteAttribute

The ObsoleteAttribute marks the code elements that are obsolete i.e. not in use anymore. Calling these obsolete code elements results in a compiler error.

Example:

filter_none

edit
close

play_arrow

link
brightness_4
code

// C# program to demonstrate ObsoleteAttribute
using System;
  
class GFG {
  
    // The method1() is marked as obsolete
    [Obsolete("method1 is obsolete", true)] static void method1()
    {
        Console.WriteLine("This is method1");
    }
  
    static void method2()
    {
        Console.WriteLine("This is method2");
    }
  
    public static void Main(string[] args)
    {
        method1(); // Compiler error as method1() is obsolete
        method2();
    }
}

chevron_right


Compile Errors:

prog.cs(18,3): error CS0619: `GFG.method1()’ is obsolete: `method1 is obsolete’

Custom Attributes

Custom attributes can be created in C# for attaching declarative information to methods, assemblies, properties, types, etc. in any way required. This increases the extensibility of the .NET framework.

Steps for creating Custom Attributes:

  • Define a custom attribute class that is derived from System.Attribute class.
  • The custom attribute class name should have the suffix Attribute.
  • Use the attribute AttributeUsage to specify the usage of the custom attribute class created.
  • Create the constructor and the accessible properties of the custom attribute class.
  • Example:

    filter_none

    edit
    close

    play_arrow

    link
    brightness_4
    code

    // C# program to demonstrate Custom Attributes
    using System;
      
    // AttributeUsage specifies the usage
    // of InformationAttribute
    [AttributeUsage(AttributeTargets.Class | AttributeTargets.Constructor | 
                            AttributeTargets.Method, AllowMultiple = true)]
      
        // InformationAttribute is a custom attribute class
        // that is derived from Attribute class
        class InformationAttribute : Attribute
        {
            public string InformationString{ get; set; }
        }
      
    // InformationAttribute is used in student class
    [Information(InformationString = "Class")] public class student
    {
      
        private int rollno;
        private string name;
      
        [Information(InformationString = "Constructor")] public student(int rollno, string name)
        {
            this.rollno = rollno;
            this.name = name;
        }
      
        [Information(InformationString = "Method")] public void display()
        {
            Console.WriteLine("Roll Number: {0}", rollno);
            Console.WriteLine("Name: {0}", name);
        }
    }
      
    // Driver Class
    public class GFG {
      
        // Main Method
        public static void Main(string[] args)
        {
            student s = new student(1001, "Lily Adams");
            s.display();
        }
    }

    chevron_right

    
    

    Output:

    Roll Number: 1001
    Name: Lily Adams
    


    My Personal Notes arrow_drop_up

    Check out this Author's contributed articles.

    If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

    Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.




    Article Tags :

    Be the First to upvote.


    Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.