Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to restrict attribute usage to only certain interfaces?

Let's say I have an interface IAppModule, implemented by a few classes. Is it at all possible to write a custom attribute that can only be applied to types that expose IAppModule? If so, how?

like image 286
ProfK Avatar asked Sep 03 '13 13:09

ProfK


People also ask

How does attributes work in C#?

In C#, attributes are classes that inherit from the Attribute base class. Any class that inherits from Attribute can be used as a sort of "tag" on other pieces of code. For instance, there is an attribute called ObsoleteAttribute . This is used to signal that code is obsolete and shouldn't be used anymore.

CAN interfaces have attributes C#?

C# Language Attributes Reading an attribute from interface 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.

What are attributes in asp net core?

With attribute-based routing, we can use C# attributes on our controller classes and on the methods internally in these classes. These attributes have metadata that tell ASP.NET Core when to call a specific controller. It is an alternative to convention-based routing.

What is attributes in. net?

Attributes are used for adding metadata, such as compiler instruction and other information such as comments, description, methods and classes to a program. The . Net Framework provides two types of attributes: the pre-defined attributes and custom built attributes.


1 Answers

No, unfortunately it's not possible.

You can, however, when using reflection to process your attributes, check if the decorated type is a class that implements the IAppModule interface.

typeof(someType).GetInterfaces().Contains(typeof(IAppModule))

It doesn't stop users of your attribute from using it incorrectly (in any other class), but if you decide to go with this approach, I'd recommend providing very clear documentation describing how the attribute should be used and adding the layer of validation I mentioned above.

like image 130
dcastro Avatar answered Oct 08 '22 06:10

dcastro