I'm developing a serialization class that uses attributes on custom classes to decorate whether a property is a fixed length format or a delimited format. These two attributes should be mutually exclusive, meaning that the developer can either specify [FixedLength]
or [Delimited]
(with appropriate constructors) on a property, but not both. In order to reduce complexity and increase cleanliness, I don't want to combine the attributes and set a flag based on the format type, e.g. [Formatted(Formatter=Formatting.Delimited)]
. Is it possible to restrict these attributes to be mutually exclusive to one another at design time? I'm aware how I can check for this scenerio at run-time.
You cannot do this in .NET. At most you can allow a single instance of the same attribute on a class, like in this example:
using System;
[AttributeUsage(AttributeTargets.Class, AllowMultiple = false)]
class BaseAttribute : Attribute {
}
[Base]
[Base] // compiler error here
class DoubleBase {
}
But this behavior cannot be extended to derived classes, i.e. if you do this it compiles:
using System;
[AttributeUsage(AttributeTargets.Class, AllowMultiple = false)]
class BaseAttribute : Attribute {
}
[AttributeUsage(AttributeTargets.Class, AllowMultiple = false)]
class Derived1Attribute : BaseAttribute {
}
[AttributeUsage(AttributeTargets.Class, AllowMultiple = false)]
class Derived2Attribute : BaseAttribute {
}
[Derived1]
[Derived2] // this one is ok
class DoubleDerived {
}
The best I can think of is that you could write something to check that there are no types with both attributes applied and use the check as a post-build step.
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