Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Restrict attribute usage to be mutually exclusive at design time?

Tags:

c#

attributes

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.

like image 698
George Johnston Avatar asked Nov 10 '11 15:11

George Johnston


1 Answers

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.

like image 83
Paolo Tedesco Avatar answered Nov 14 '22 22:11

Paolo Tedesco