Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Force usage of custom attribute

Tags:

c#

attributes

Scenario: I have a base class "MyBase". I have a custom attribute "MyAttrib"

With that I do this:

[MyAttrib(1234)] class MyClass : MyBase() {  MyClass()  {  } } 

Question: Can I in any way force classes inherting from MyBase to have the attribute MyAttrib?

like image 374
ToPa Avatar asked Jun 10 '09 10:06

ToPa


People also ask

What is the use of custom attributes?

A custom attribute is a property that you can define to describe assets. Custom attributes extend the meaning of an asset beyond what you can define with the standard attributes. You can create a custom attribute and assign to it a value that is an integer, a range of integers, or a string.

Is it possible to modify object properties run time?

The only way you can define new attributes at run time is to generate new code at runtime (using Reflection. Emit, for example). But you cannot change the attributes of existing code.

What are the custom attributes in net?

NET custom attributes. Attributes are key-value pairs containing information that determines the properties of an event or transaction. You can create custom attributes using the AddCustomAttribute API.


2 Answers

No, there is no way to have the compiler require an attribute in C#. You do have some other options available to you. You could write a unit test that reflects on all types in the assembly and checks for the attribute. But unfortunately there is no way to have the compiler force the usage of an attribute.

like image 187
Andrew Hare Avatar answered Oct 05 '22 15:10

Andrew Hare


No longer relevant to the original poster I imagine, but here's something for anyone who's curious like I was if this was doable.

The following works, but sadly it's not a compile-time check and as such I can't honestly recommend it used. You're better off with interfaces, virtuals and abstracts for most things.

The required attribute:

[AttributeUsage(AttributeTargets.Class, AllowMultiple = false, Inherited = false)] public class RequiredRandomThingAttribute : Attribute { /* ... */ } 

Parent class that requires it for derived classes:

public class ParentRequiringAttribute {     public ParentRequiringAttribute()     {         if (this.GetType().GetCustomAttributes(typeof(RequiredRandomThingAttribute), false).Length == 0)             throw new NotImplementedException(this.GetType().ToString());     } } 

And to confirm it all works:

[RequiredRandomThing()] public class CompleteSubclass : ParentRequiringAttribute { /* ... */ }  public class IncompleteSubclass : ParentRequiringAttribute { /* ... */ }  static public int Main(string[] args) {     var test1 = new CompleteSubclass();     var test2 = new IncompleteSubclass(); // throws } 

It should be fairly easy to improve the validation, but my own investigation stopped here.

like image 25
MKAh Avatar answered Oct 05 '22 14:10

MKAh