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(); } } } }