I don’t really understand attributes. I’ve read all kinds of books & posts on them, but I just don’t get it.
Since I don’t understand them, I also don’t understand how to effectively use them.
1) Can you give me a good definition of what an attribute is & what it’s used for?
2) Can you give me a good code example in C# of how to make and consume a custom attribute?
Say you’ve got a class with a series of properties that you are going to walk through using reflection. Any that are strings may need to be validated to check they are not longer than a certain amount.
You could then create a
TextLengthattribute, with a default integer constructor and integer property/field. You could then read your attribute on each string property in your class and compare the length of the property value to the number specified in the attribute.Code:
Note: untested