Reputation: 2695
I'm starting to learn about custom attributes and I have one question for the more experienced users:
I want to mark my properties as "TypeA" or "TypeB" with attributes, so I can check them with reflection. Is it better to have only one attribute with state, like this:
Public Class FlavourAttribute
Inherits Attribute
Private _flavour As Flavours
Public ReadOnly Property Flavour() As Flavours
Get
Return _flavour
End Get
End Property
Public Enum Flavours
Sweet = 0
Acid = 1
End Enum
Public Sub New(ByVal flavour As Flavours)
_flavour = flavour
End Sub
End Class
Or is it better to use two attributes without state:
Public Class SweetAttribute
Inherits Attribute
End Class
Public Class AcidAttribute
Inherits Attribute
End Class
I'm asking about drawbacks of these two approaches, or possible alternatives.
Thanks!
Upvotes: 0
Views: 69
Reputation: 2695
After a while of playing with custom attributes I would say I've discovered a good reason to prefer separate attributes over one single attribute with state: it is far more simple and readable to check if one property has a single attribute than checking a property of the attribute.
Following with the example in the question, with separate attributes, we would have:
For Each prop As PropertyInfo In MyTipe.GetProperties
thePropertyIsSweet= Attribute.IsDefined(prop , GetType(SweetAttribute))
thePropertyIsAcid= Attribute.IsDefined(prop , GetType(AcidAttribute))
Next
While with a single attribute with state I should first check if the property has it, then cast an attribute object from it and retrieve its two properties.
I'm a wrong with this reasoning?
Upvotes: 0
Reputation: 185623
There's not an answer to your general question, but the answer to your specific question would be to use the latter. Whether or not something is sweet is independent of whether or not it's acidic, so you're talking about different things. If, on the other hand, you were dealing with related (or mutually exclusive) properties, they should be on one attribute.
Upvotes: 1