0
0
C Sharp (C#)programming~5 mins

Attribute targets and usage in C Sharp (C#) - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
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?
AAttributeTargets.Field
BAttributeTargets.Method
CAttributeTargets.Class
DAttributeTargets.Property
How do you allow an attribute to be used multiple times on the same target?
AUse multiple attribute declarations
BSet AllowMultiple = true in AttributeUsage
CSet Inherited = true in AttributeUsage
DUse AttributeTargets.All
What is the default target if AttributeUsage is not specified?
AAll targets
BClass only
CMethod only
DProperty only
Which of these is NOT a valid AttributeTargets value?
AAttributeTargets.Interface
BAttributeTargets.Event
CAttributeTargets.Namespace
DAttributeTargets.Parameter
What does setting Inherited = false in AttributeUsage do?
APrevents derived classes from inheriting the attribute
BAllows multiple attributes on the same target
CRestricts attribute to methods only
DMakes attribute internal
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.