Attributes in C# - GeeksforGeeks

01 May, 2019
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:
Predefined AttributesCustom Attributes
Predefined Attributes
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.
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:
Let’s discuss some of the predefined attributes:
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.
// C# program to demonstrate CLSCompliantAttributeusing System;  // CLSCompliantAttribute applied to entire assembly[assembly:CLSCompliant(true)]      public class GFG {      // Main Method    public static void Main(string[] args)    {        Console.WriteLine("GeeksForGeeks");    }}
GeeksForGeeks

Example 2: This code will give a warning message by the compiler.
// C# program to demonstrate CLSCompliantAttribute// giving a warning messageusing System;  // CLSCompliantAttribute applied to entire assembly[assembly:CLSCompliant(true)]      public class GFG {    public uint z;}  class GFG2 {  // Main Methodpublic static void Main(string[] args){    Console.WriteLine("GeeksForGeeks");}  }
Warning:
prog.cs(9,14): warning CS3003: Type of `GFG.z’ is not CLS-compliant
The FlagsAttribute specifies that an enumeration can be used as a set of flags. This is most commonly used with bitwise operators.
Example:
// C# program to demonstrate FlagsAttributeusing 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());    }}
3
Red, Blue

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:
// C# program to demonstrate ObsoleteAttributeusing 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();    }}
Compile Errors:
prog.cs(18,3): error CS0619: `GFG.method1()’ is obsolete: `method1 is obsolete’
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:// C# program to demonstrate Custom Attributesusing 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 Classpublic class GFG {      // Main Method    public static void Main(string[] args)    {        student s = new student(1001, "Lily Adams");        s.display();    }}Output:Roll Number: 1001
Name: Lily Adams
My Personal Notes
arrow_drop_upSave
Example:
// C# program to demonstrate Custom Attributesusing 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 Classpublic class GFG {      // Main Method    public static void Main(string[] args)    {        student s = new student(1001, "Lily Adams");        s.display();    }}
Roll Number: 1001
Name: Lily Adams

C#
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
C# Dictionary with examples
C# | Delegates
C# | Abstract Classes
Difference between Ref and Out keywords in C#
Extension Method in C#
C# | String.IndexOf( ) Method | Set - 1
C# | Replace() Method
Introduction to .NET Framework
C# | Data Types
C# | Arrays