Attributes in C# are a type of metadata that you can add to your code to provide additional information about types, methods, properties, and other program elements. Attributes are used by the compiler, runtime, and other tools to modify the behavior of the program or to provide additional information about it.
In C#, attributes are defined using the `System.Attribute` class, which is the base class for all attributes. Attributes can be applied to program elements using square brackets, and can take parameters that specify their behavior.
Here’s an example of defining and using a custom attribute:
[AttributeUsage(AttributeTargets.Method)] class MyAttribute : Attribute { public string Message { get; set; } public MyAttribute(string message) { Message = message; } } class MyClass { [My("Hello, world!")] public void MyMethod() { Console.WriteLine("Hello, world!"); } } class Program { static void Main(string[] args) { MyClass obj = new MyClass(); MethodInfo method = typeof(MyClass).GetMethod("MyMethod"); MyAttribute attribute = (MyAttribute)method.GetCustomAttributes(typeof(MyAttribute), false)[0]; Console.WriteLine(attribute.Message); obj.MyMethod(); } }
In this example, a custom attribute called `MyAttribute` is defined. This attribute takes a parameter called `message`, which is used to specify a message that will be printed when the method is called.The `MyMethod` method of the `MyClass` class is decorated with the `My` attribute, which specifies a message of “Hello, world!”. The `Main` method of the program uses reflection to get the `MyMethod` method, and then gets the `MyAttribute` object that was applied to it. The program then prints the message specified by the attribute, and calls the `MyMethod` method.
Attributes can be used for a variety of purposes, such as providing additional information to documentation tools, modifying the behavior of code generators, controlling the serialization of objects, and more. Many built-in attributes are provided by the .NET Framework, such as the `ObsoleteAttribute`, which marks a program element as obsolete and generates a warning when it is used.
Overall, attributes are a powerful feature in C# that allow you to add metadata to your code and modify the behavior of your program. By using attributes, you can make your code more expressive, flexible, and maintainable.