Bird
Raised Fist0
C Sharp (C#)programming~10 mins

Attribute targets and usage in C Sharp (C#) - Step-by-Step Execution

Choose your learning style10 modes available
Concept Flow - Attribute targets and usage
Define Attribute
↓
Specify Target(s)
↓
Apply Attribute to Target
↓
Compile and Use Reflection
↓
Access Attribute Info
This flow shows how to define an attribute, specify where it can be used, apply it, then access it at runtime.
Execution Sample
C Sharp (C#)
using System;

[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)]
class MyInfoAttribute : Attribute { }

[MyInfo]
class Sample {
  [MyInfo] public void Test() { }
}
Defines an attribute usable on classes and methods, then applies it to a class and a method.
Execution Table
StepActionTargetAttribute AppliedResult
1Define MyInfoAttributeN/AN/AAttribute class created
2Specify AttributeUsageClass, MethodMyInfoAttributeLimits usage to classes and methods
3Apply [MyInfo] to class SampleClass SampleMyInfoAttributeAttribute attached to class
4Apply [MyInfo] to method TestMethod TestMyInfoAttributeAttribute attached to method
5Compile and run reflectionSample classMyInfoAttributeDetects attribute on class and method
6ExitN/AN/AExecution complete
💡 All attribute targets applied and detected, execution ends
Variable Tracker
VariableStartAfter Step 2After Step 4Final
MyInfoAttributeundefineddefined with targets Class, Methodapplied to Sample and Testavailable via reflection
Key Moments - 2 Insights
Why do we specify AttributeTargets in AttributeUsage?
Specifying AttributeTargets restricts where the attribute can be applied, as shown in step 2 of the execution_table. Without it, the attribute could be used anywhere, which may cause errors.
Can we apply the attribute to a property if AttributeTargets only includes Class and Method?
No. The attribute usage limits in step 2 mean applying it to a property would cause a compile error. This is why step 3 and 4 only show class and method targets.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, at which step is the attribute usage restricted to classes and methods?
AStep 1
BStep 2
CStep 3
DStep 4
💡 Hint
Check the 'Specify AttributeUsage' action in the execution_table at step 2
According to variable_tracker, what is the state of MyInfoAttribute after step 4?
AUndefined
BDefined but not applied
CApplied to Sample and Test
DRemoved
💡 Hint
Look at the 'After Step 4' column for MyInfoAttribute in variable_tracker
If we tried to apply [MyInfo] to a property, what would happen based on the execution flow?
AIt would cause a compile error
BIt would compile and run fine
CIt would be ignored at runtime
DIt would apply only to methods
💡 Hint
Refer to the AttributeTargets restriction in step 2 of execution_table
Concept Snapshot
Define an attribute class by inheriting Attribute.
Use [AttributeUsage] to specify valid targets (e.g., Class, Method).
Apply attribute with [YourAttribute] on allowed targets.
At runtime, use reflection to check attribute presence.
Restricting targets prevents incorrect usage and compile errors.
Full Transcript
This example shows how to create a custom attribute in C# and control where it can be applied using AttributeTargets. First, we define the attribute class MyInfoAttribute. Then, we specify that it can only be used on classes and methods with AttributeUsage. Next, we apply the attribute to a class named Sample and its method Test. Finally, at runtime, reflection can detect these attributes. This prevents applying the attribute to unsupported targets like properties, which would cause compile errors.

Practice

(1/5)
1. What does the AttributeUsage attribute control in C#?
easy
A. The visibility of a class
B. The return type of a method
C. Where an attribute can be applied (e.g., class, method, property)
D. The inheritance of a class

Solution

  1. Step 1: Understand the purpose of AttributeUsage

    The AttributeUsage attribute specifies the valid program elements (targets) where a custom attribute can be applied, such as classes, methods, or properties.
  2. Step 2: Eliminate unrelated options

    Options about return types, visibility, or inheritance are unrelated to attribute targets.
  3. Final Answer:

    Where an attribute can be applied (e.g., class, method, property) -> Option C
  4. Quick Check:

    AttributeUsage controls attribute targets = C [OK]
Hint: AttributeUsage sets where attributes can be placed [OK]
Common Mistakes:
  • Confusing AttributeUsage with method or class modifiers
  • Thinking it controls inheritance or visibility
  • Assuming it changes method return types
2. Which of the following is the correct syntax to allow an attribute to be applied only to methods?
easy
A. [AttributeUsage(AttributeTargets.Method)]
B. [AttributeUsage(AttributeTargets.Class)]
C. [AttributeUsage(AttributeTargets.Property)]
D. [AttributeUsage(AttributeTargets.Field)]

Solution

  1. Step 1: Identify the target for methods

    The AttributeTargets.Method enum value specifies that the attribute can only be applied to methods.
  2. Step 2: Match the syntax

    The correct syntax uses [AttributeUsage(AttributeTargets.Method)] to restrict usage to methods.
  3. Final Answer:

    [AttributeUsage(AttributeTargets.Method)] -> Option A
  4. Quick Check:

    Method target uses AttributeTargets.Method = B [OK]
Hint: Use AttributeTargets.Method to target methods only [OK]
Common Mistakes:
  • Using Class or Property targets instead of Method
  • Forgetting square brackets around AttributeUsage
  • Misspelling AttributeTargets
3. What will happen if you apply this attribute to a class?
[AttributeUsage(AttributeTargets.Method)]
public class MyAttribute : Attribute { }

[MyAttribute]
public class TestClass { }
medium
A. Compilation error because attribute is applied to a class, not a method
B. The attribute is applied successfully to the class
C. Runtime error when the program runs
D. Warning but code compiles

Solution

  1. Step 1: Check the AttributeUsage target

    The attribute MyAttribute is restricted to methods only by AttributeTargets.Method.
  2. Step 2: Analyze the application

    Applying [MyAttribute] to a class violates the target restriction, causing a compilation error.
  3. Final Answer:

    Compilation error because attribute is applied to a class, not a method -> Option A
  4. Quick Check:

    Wrong target usage causes compile error = D [OK]
Hint: AttributeUsage restricts targets; wrong target causes compile error [OK]
Common Mistakes:
  • Assuming attribute applies anyway without error
  • Thinking error happens at runtime
  • Ignoring AttributeUsage restrictions
4. Identify the error in this code snippet:
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = false)]
public class InfoAttribute : Attribute { }

[Info]
[Info]
public class Sample { }
medium
A. No error, multiple attributes allowed
B. Error because AllowMultiple is false but attribute applied twice
C. Error because AttributeTargets is missing Property
D. Error because attribute class must be sealed

Solution

  1. Step 1: Understand AllowMultiple property

    The AllowMultiple = false means the attribute cannot be applied more than once on the same element.
  2. Step 2: Check attribute usage on Sample class

    The [Info] attribute is applied twice on the same class, violating the AllowMultiple restriction.
  3. Final Answer:

    Error because AllowMultiple is false but attribute applied twice -> Option B
  4. Quick Check:

    AllowMultiple false + multiple uses = error [OK]
Hint: AllowMultiple false forbids multiple attribute uses [OK]
Common Mistakes:
  • Ignoring AllowMultiple setting
  • Thinking multiple attributes are always allowed
  • Confusing AttributeTargets with AllowMultiple
5. You want to create an attribute that can be applied to classes, methods, and properties, and allow multiple uses on the same element. Which is the correct AttributeUsage declaration?
hard
A. [AttributeUsage(AttributeTargets.Property, AllowMultiple = true)]
B. [AttributeUsage(AttributeTargets.All, AllowMultiple = false)]
C. [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = false)]
D. [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method | AttributeTargets.Property, AllowMultiple = true)]

Solution

  1. Step 1: Combine targets for classes, methods, and properties

    Use bitwise OR to combine AttributeTargets.Class, AttributeTargets.Method, and AttributeTargets.Property.
  2. Step 2: Set AllowMultiple to true

    To allow multiple uses on the same element, set AllowMultiple = true.
  3. Final Answer:

    [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method | AttributeTargets.Property, AllowMultiple = true)] -> Option D
  4. Quick Check:

    Combine targets + AllowMultiple true = A [OK]
Hint: Use bitwise OR for multiple targets and AllowMultiple true [OK]
Common Mistakes:
  • Using AllowMultiple false when multiple uses needed
  • Missing some targets in the bitwise OR
  • Using AttributeTargets.All when not needed
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard