Recall & Review
beginner
What is an attribute target in C#?
An attribute target specifies where an attribute can be applied, such as a class, method, property, or assembly.
Click to reveal answer
beginner
How do you specify that an attribute can only be used on methods?
Use [AttributeUsage(AttributeTargets.Method)] above the attribute class definition.Click to reveal answer
intermediate
What does the AttributeUsage attribute control?
It controls where the custom attribute can be applied and whether it can be applied multiple times or inherited.
Click to reveal answer
intermediate
Can an attribute be applied to multiple targets? How?
Yes, by combining targets using a bitwise OR, for example: [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)].
Click to reveal answer
beginner
What happens if you apply an attribute to a target not allowed by its AttributeUsage?
The compiler will show an error because the attribute is used on an invalid target.
Click to reveal answer
Which AttributeTargets value allows an attribute to be applied to properties?
✗ Incorrect
AttributeTargets.Property is used to specify that an attribute can be applied to properties.
How do you allow an attribute to be used multiple times on the same target?
✗ Incorrect
AllowMultiple = true in AttributeUsage allows applying the attribute multiple times on the same target.
What is the default target if AttributeUsage is not specified?
✗ Incorrect
By default, attributes can be applied to all targets if AttributeUsage is not specified.
Which of these is NOT a valid AttributeTargets value?
✗ Incorrect
AttributeTargets.Namespace does not exist; namespaces cannot have attributes.
What does setting Inherited = false in AttributeUsage do?
✗ Incorrect
Inherited = false means the attribute is not inherited by derived classes.
Explain how to restrict a custom attribute to be used only on classes and methods.
Think about combining targets with a bitwise OR.
You got /3 concepts.
Describe what happens if you try to apply an attribute to a target not allowed by its AttributeUsage.
Consider compiler checks for attribute placement.
You got /3 concepts.