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?
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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With