Page 147 - CSharp/C#
P. 147
private static void GetInterfaceAttributeDemo() {
var attribute1 = (MyCustomAttribute)
typeof(MyClass).GetCustomAttribute(typeof(MyCustomAttribute), true);
Console.WriteLine(attribute1 == null); // True
var attribute2 =
typeof(MyClass).GetCustomAttributes(true).OfType<MyCustomAttribute>().SingleOrDefault();
Console.WriteLine(attribute2 == null); // True
var attribute3 = typeof(MyClass).GetCustomAttribute<MyCustomAttribute>(true);
Console.WriteLine(attribute3 == null); // True
}
}
}
One way to retrieve interface attributes is to search for them through all the interfaces
implemented by a class.
var attribute = typeof(MyClass).GetInterfaces().SelectMany(x =>
x.GetCustomAttributes().OfType<MyCustomAttribute>()).SingleOrDefault();
Console.WriteLine(attribute == null); // False
Console.WriteLine(attribute.Text); // Hello from interface attribute
Obsolete Attribute
System.Obsolete is an attribute that is used to mark a type or a member that has a better version,
and thus should not be used.
[Obsolete("This class is obsolete. Use SomeOtherClass instead.")]
class SomeClass
{
//
}
In case the class above is used, the compiler will give the warning "This class is obsolete. Use
SomeOtherClass instead."
Read Attributes online: https://riptutorial.com/csharp/topic/1062/attributes
https://riptutorial.com/ 93

