TheDeveloperBlog.com

Home | Contact Us

C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML

<< Back to C-SHARP

C# Attribute Examples

Use attributes like Obsolete and AttributeUsage. Specify an attribute that is used on classes.
Attribute. The C# language can be extended. Attributes extend classes and types. This C# feature allows you to attach declarative information to any type.Class
Some details. Attributes are accessed at compile-time or runtime through the metadata. We then can handle types based on their attributes.
This program provides an example of the Obsolete attribute. The Obsolete attribute is a way to declare that a method is deprecated and should be avoided.Obsolete

Info: When you look at the program in Visual Studio, this will result in a warning.

Tip: The actual type referenced by [Obsolete] is ObsoleteAttribute, but you can omit the word Attribute.

Tip 2: The attribute modifies the compiler's view of the Program.Text method. It doesn't affect runtime.

C# program that uses attribute using System; class Program { static void Main() { // Warning: 'Program.Test()' is obsolete Test(); } [Obsolete] static void Test() { } } Warning generated by program: 'Program.Test()' is obsolete
Syntax. An attribute is a class that is derived from the Attribute class through inheritance. Often, we put an attribute on the class itself.

Note: This provides a way to specify what kind of types the attribute applies to, among other options.

Note 2: We specify to use the attribute with square brackets and the name of the attribute, omitting the word "Attribute" on the end.

PerlsAttribute: This is an attribute class that can only be attached to class types—not fields, methods, or properties.

C# program that declares attribute using System; /// <summary> /// An attribute that can only be attached to classes. /// </summary> [AttributeUsage(AttributeTargets.Class)] public class PerlsAttribute : Attribute { } /// <summary> /// Use short syntax to reference attribute. /// </summary> [Perls] class Example1 { } /// <summary> /// Use long syntax to reference attribute. /// </summary> [PerlsAttribute] class Example2 { } class Program { static void Main() { // For compilation. } }
Members. This example includes a string member field, a property accessor to that field, and a constructor. With this version of PerlsAttribute, we must use a string parameter.
C# program that uses attributes, number 2 using System; /// <summary> /// Attribute. /// </summary> [AttributeUsage(AttributeTargets.Class)] public class PerlsAttribute : Attribute { /// <summary> /// Stores string field. /// </summary> string _id; /// <summary> /// Attribute constructor. /// </summary> public PerlsAttribute(string id) { this._id = id; } /// <summary> /// Get Id. /// </summary> public string Id { get { return this._id; } } } /// <summary> /// Apply attribute. /// </summary> [Perls("Dot")] class Example1 { } class Program { static void Main() { // For compilation. } }
Positional, named. The C# specification recommends that named parameters be used. They are not as likely to be invalidated when the attribute declaration changes.

Positions: With positional parameters, you rely on the position of the parameters in the constructor.

Constructor

However: With named parameters, you simply rely on having specified the correct name.

C# program that uses attributes, number 3 using System; /// <summary> /// Attribute. /// </summary> [AttributeUsage(AttributeTargets.Class)] public class PerlsAttribute : Attribute { /// <summary> /// String field. /// </summary> string _id; /// <summary> /// Attribute constructor. /// </summary> public PerlsAttribute() { } /// <summary> /// Get and set. /// </summary> public string Id { get { return this._id; } set { this._id = value; } } } /// <summary> /// Set property in the attribute. /// </summary> [Perls(Id = "Sam")] class Example1 { } class Program { static void Main() { // For compilation. } }
AllowMultiple. By default an attribute can only be specified a single time on a member or type declaration. To bypass this restriction, use AllowMultiple.
Conditional. A Conditional attribute can disable or enable certain methods depending on whether the compilation mode is DEBUG or RELEASE. These methods must have a void return type.Conditional
Flags. The enum type in the C# language has the [Flags] attribute. This can be used to set multiple enum values at once. Bitwise operators are used.Enum Flags
DllImport. Attributes help with the task of using external code such as C++ or C. The DllImport attribute can be attached to extern method declarations.DllImport, Dllexport

Warning: Whenever you need to use DllImport, you are bound to have difficulties. Interop introduces extra layers of complexity.

Reflection. How can you use attributes in a simple program? You can use the reflection feature in the C# language to access attributes at runtime.Reflection

Example: Get an array of all the fields in your type. Then perform an action based on what data the attribute of each type contains.

Compiler. Attributes can be accessed during compile-time. And the compiler can take different actions based on what data is contained in the attribute.

Info: In compiler theory, the attribute data would become part of the symbol table.

And: The symbol table is used throughout the construction of the object code in further compiler phases.

Quote: C# enables programmers to invent new kinds of declarative information, called attributes (The C# Programming Language).

A summary. Custom attributes are of fairly limited use. But they provide many options for extensibility. With them we attach declarative information to members and types.
© TheDeveloperBlog.com
The Dev Codes

Related Links:


Related Links

Adjectives Ado Ai Android Angular Antonyms Apache Articles Asp Autocad Automata Aws Azure Basic Binary Bitcoin Blockchain C Cassandra Change Coa Computer Control Cpp Create Creating C-Sharp Cyber Daa Data Dbms Deletion Devops Difference Discrete Es6 Ethical Examples Features Firebase Flutter Fs Git Go Hbase History Hive Hiveql How Html Idioms Insertion Installing Ios Java Joomla Js Kafka Kali Laravel Logical Machine Matlab Matrix Mongodb Mysql One Opencv Oracle Ordering Os Pandas Php Pig Pl Postgresql Powershell Prepositions Program Python React Ruby Scala Selecting Selenium Sentence Seo Sharepoint Software Spellings Spotting Spring Sql Sqlite Sqoop Svn Swift Synonyms Talend Testng Types Uml Unity Vbnet Verbal Webdriver What Wpf