TheDeveloperBlog.com

Home | Contact Us

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

C# Attribute Examples

This C# tutorial shows how to use attributes. It uses Obsolete and AttributeUsage.

Attributes extend classes and types.

This C# feature allows you to attach declarative information to any type. Attributes are accessed at compile-time or runtime through the metadata. We then can handle types based on their attributes.

Example. 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. When you look at the program in Visual Studio, this will result in a warning.

Visual Studio

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.

Compiler

Based on:

.NET 4.5

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

The .NET Framework provides useful built-in attribute types. The Obsolete attribute is one of them. It causes annoying warnings when a developer tries to compile a program containing a method that the obsolete attribute is attached to.

Obsolete

Declare attribute. An attribute is a class that is derived from the Attribute class through inheritance. Often, we put an attribute on the class itself. This provides a way to specify what kind of types the attribute applies to, among other options.

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

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

AttributeTargets.Class. The class PerlsAttribute is an attribute class that can only be attached to class types. It cannot be attached to fields, methods, or properties, for example.

Also: Please notice how you can omit specifying the entire "PerlsAttribute" in the example. You can just use "Perls" optionally.

Members. This example builds on the previous one. It includes a string member field, a property accessor to that field, and a parameterful (positional) constructor. With this version of PerlsAttribute, we must specify a string type parameter.

Note: Parameterful is a real word. I did not just make it up. Someone else made it up.

Example attribute program 2: C#

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 specification recommends that named parameters be used. They are not as likely to be invalidated when the attribute declaration changes. 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.

Tip: For a positional parameter, please remember to include the set accessor. You can combine positional and named parameters.

Example attribute program 3: C#

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, you must set the AllowMultiple boolean named parameter to true.

True

Conditional. The Conditional attribute is typically used to disable or enable certain methods depending on whether the compilation mode is DEBUG or RELEASE. These methods must have a void return type.

ConditionalVoidReturn

Flags. The enum type in the C# language has the [Flags] attribute and this can be used to create some useful functions. Please visit the flags article and also the enum category for more on enumerated types.

FlagsEnum

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. This provides a compile-time signal that allows a program that uses external calls.

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

DllImport, Dllexport

Reflection. How can you use attributes in a simple program—one where you do not want to develop your own compiler technology? You can use the reflection feature in the C# language to access attributes at runtime.

For example, try getting an array of all the fields in your type, and then performing a different action based on what data the attribute of each type contains. This is sometimes useful for developing debugging mechanisms.

Reflection and System.Reflection

Compiler. Attributes can be accessed during compile-time. And the compiler can take different actions based on what data is contained in the attribute. 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.

Summary. Custom attributes are of fairly limited use in most programs, but they provide nearly infinite options for extensibility. With them we attach declarative information to members and types. And we essentially build new languages.


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