using System; [AttributeUsage(AttributeTargets.Class)] public class DescriptionAttribute : Attribute { private readonly string _description; public DescriptionAttribute(string description) { _description = description; } public string Description { get { return _description; } } } [Description("This is a description of MyClass.")] public class MyClass { // ... } class Program { static void Main(string[] args) { DescriptionAttribute attr = (DescriptionAttribute)Attribute.GetCustomAttribute(typeof(MyClass), typeof(DescriptionAttribute)); Console.WriteLine(attr.Description); } }
using System; class Program { [Obsolete("This method is no longer recommended. Please use SomeOtherMethod instead.")] static void OldMethod() { // ... } static void SomeOtherMethod() { // ... } static void Main(string[] args) { OldMethod(); // Generates a warning ObsoleteAttribute attr = (ObsoleteAttribute)Attribute.GetCustomAttribute(typeof(Program).GetMethod("OldMethod"), typeof(ObsoleteAttribute)); Console.WriteLine(attr.Message); } }This code defines two methods, "OldMethod" and "SomeOtherMethod". The OldMethod method is marked with the Obsolete attribute, which indicates that it is no longer recommended for use. When OldMethod is called, a warning is generated indicating that the method is obsolete. The GetAttribute method is then used to retrieve the value of the Obsolete attribute applied to the OldMethod method. The message provided by the Obsolete attribute is then printed to the console. In both examples, the GetAttribute method is part of the System namespace in C#. Specifically, it is part of the System.Reflection namespace, which provides a range of features for working with code at runtime.