Attributes in C#
Attributes are used to add metadata to code elements such as classes, methods, properties, etc. The metadata can be used by tools and libraries to provide additional functionality. C# provides several built-in attributes such as [Serializable], [Obsolete], [DllImport], etc. Here's an example code that demonstrates how to define and use a custom attribute:
[AttributeUsage(AttributeTargets.Class)]
class MyAttribute : Attribute
{
public string Name { get; set; }
public MyAttribute(string name)
{
Name = name;
}
}
[My("Test")]
class MyClass
{
}
MyAttribute attr = (MyAttribute)Attribute.GetCustomAttribute(typeof(MyClass), typeof(MyAttribute));
Console.WriteLine(attr.Name); // prints "Test"
No comments:
Post a Comment