[Description("This is a sample class")] class MyClass { // class properties and methods } // Usage Type myClassType = typeof(MyClass); object[] myClassAttributes = myClassType.GetCustomAttributes(typeof(DescriptionAttribute), false); DescriptionAttribute myClassDescription = (DescriptionAttribute)myClassAttributes[0]; Console.WriteLine(myClassDescription.Description); // Output: "This is a sample class"
class MyClass { [Author("John Doe")] public void MyMethod() { // method code } } // Usage MethodInfo myMethod = typeof(MyClass).GetMethod("MyMethod"); object[] myMethodAttributes = myMethod.GetCustomAttributes(typeof(AuthorAttribute), false); AuthorAttribute myMethodAuthor = (AuthorAttribute)myMethodAttributes[0]; Console.WriteLine(myMethodAuthor.Name); // Output: "John Doe"In both these examples, we can see that the GetCustomAttributes method is used to retrieve the custom attributes applied to the specified object (class or method) and cast them to their respective attribute types. We can then access the attribute properties, such as Description or Author Name, and use them as required in our program. The package library used in both these examples is the System.Reflection namespace, which is a part of the .NET Framework.