Reading an attribute from interface C# with Example



Reading an attribute from interface C# with Example

There is no simple way to obtain attributes from an interface, since classes does not inherit attributes from an 
interface. Whenever implementing an interface or overriding members in a derived class, you need to re-declare 
the attributes. So in the example below output would be True in all three cases. 
using System; 
using System.Linq; 
using System.Reflection; 
namespace InterfaceAttributesDemo { 
[AttributeUsage(AttributeTargets.Interface, Inherited = true)] 
class MyCustomAttribute : Attribute { 
public string Text { get; set; } 
} 
[MyCustomAttribute(Text = "Hello from interface attribute")] 
interface IMyClass { 
void MyMethod(); 
} 
class MyClass : IMyClass { 
public void MyMethod() { } 
} 
public class Program { 
public static void Main(string[] args) { 
GetInterfaceAttributeDemo(); 
} 
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().SingleOrDefault(); 
Console.WriteLine(attribute2 == null); // True 
var attribute3 = typeof(MyClass).GetCustomAttribute(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()).SingleOrDefault(); 
Console.WriteLine(attribute == null); // False 
Console.WriteLine(attribute.Text); // Hello from interface attribute 
 

0 Comment's

Comment Form

Submit Comment