Tuesday, 21 August 2018

C#: Attributes

Attributes can be attached to class, method, namespace, assembly etc., they provide useful information to the developer. As per the syntax, attributes should be declared inside [].

For example, I decorated, ‘printMessage’ method with ‘Obsolete’ attribute. 


class Demo
{
    [Obsolete]
    public static void printMessage(String message)
    {

    }

    public static void displayMessage(String message)
    {

    }
}

When any class tries to use the method ‘printMessage’, then C# shows an alert by saying ‘printMessage’ method is deprecated.




Following is the complete working application.

Program.cs

using System;

class Demo
{
    [Obsolete]
    public static void printMessage(String message)
    {

    }

    public static void displayMessage(String message)
    {

    }
}
class Program
{
   
    static void Main(string[] args)
    {
        Demo.printMessage("Hello World");
    }
}

You can also add meaningful information to the Obsolete attribute by passing string argument.

Example
    [Obsolete("Use displayMessage method")]
    public static void printMessage(String message)
    {


    }


Previous                                                 Next                                                 Home

No comments:

Post a Comment