C# Attributes

C# Code Snippets Attributes
Share:

About

In this code snippet, we will take a look at attributes in C#.

Attributes are used to add additional information(metadata) to code. For example, you can use [Serializable] to indicate that a class can be serialized. Or as I will demonstrate in the code example a method can be marked as obsolete and Visual Studio will warn you when you attempt to use the obsolete method. 

There are also assembly attributes that can be used to set things like the assembly version, culture, title, etc. Here is a practical example of an assembly level attribute being used to give access to all types marked with the internal access modifier to another assembly.

Note: You can even create your own custom attributes.

Let’s look at the code example below to see how to use attributes.

Code:

using System;

namespace Attributes
{
    class Program
    {
        static void Main(string[] args)
        {
            HelloClass.helloMethod();

            HelloClass.helloMethod("Me");
        }
    }

    class HelloClass
    {
        [ObsoleteAttribute("Use helloMethod(\"name\"). If there is no name put in an empty string as parameter.")]
        public static void helloMethod() 
        {
            Console.WriteLine("Hello World");
            Console.ReadLine();
        }

        public static void helloMethod(string name)
        {
            if (name == "")
            {
                Console.WriteLine("Hello World");
                Console.ReadLine();
            }
            else
            {
                Console.WriteLine("Hello " + name);
                Console.ReadLine();
            }
        }
    }
}
As you can see Visual Studio warns us that the method we are trying to invoke(call) is obsolete and displays the message we typed in earlier.

Resulting output:

Share:

Leave a Reply

Your email address will not be published. Required fields are marked *

The following GDPR rules must be read and accepted:
This form collects your name, email and content so that we can keep track of the comments placed on the website. For more info check our privacy policy where you will get more info on where, how and why we store your data.

Advertisment ad adsense adlogger