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

Attribute targets and usage in C Sharp (C#) - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Attribute Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate
2:00remaining
Output of attribute usage on method
What is the output when the following C# program runs?
C Sharp (C#)
using System;

[AttributeUsage(AttributeTargets.Method)]
public class InfoAttribute : Attribute
{
    public string Text { get; }
    public InfoAttribute(string text) => Text = text;
}

class Program
{
    [Info("Test method")]
    public static void Display() => Console.WriteLine("Hello World");

    static void Main()
    {
        var method = typeof(Program).GetMethod("Display");
        var attr = (InfoAttribute)Attribute.GetCustomAttribute(method, typeof(InfoAttribute));
        Console.WriteLine(attr.Text);
        Display();
    }
}
ATest method\nHello World
BHello World\nTest method
CHello World
DCompilation error
Attempts:
2 left
💡 Hint
Look at how the attribute is retrieved and printed before calling the method.
❓ Predict Output
intermediate
2:00remaining
Attribute usage on class and property
What will be the output of this C# code?
C Sharp (C#)
using System;

[AttributeUsage(AttributeTargets.Class | AttributeTargets.Property)]
public class LabelAttribute : Attribute
{
    public string Name { get; }
    public LabelAttribute(string name) => Name = name;
}

[Label("Person Class")]
class Person
{
    [Label("Person Name")]
    public string Name { get; set; }
}

class Program
{
    static void Main()
    {
        var classAttr = (LabelAttribute)Attribute.GetCustomAttribute(typeof(Person), typeof(LabelAttribute));
        var propAttr = (LabelAttribute)Attribute.GetCustomAttribute(typeof(Person).GetProperty("Name"), typeof(LabelAttribute));
        Console.WriteLine(classAttr.Name);
        Console.WriteLine(propAttr.Name);
    }
}
ACompilation error
BPerson Name\nPerson Class
CPerson Class\nPerson Name
DPerson Class
Attempts:
2 left
💡 Hint
Check which targets the attribute is allowed on and where it is applied.
❓ Predict Output
advanced
2:00remaining
Effect of AttributeUsage AllowMultiple = true
What is the output of this program?
C Sharp (C#)
using System;
using System.Linq;

[AttributeUsage(AttributeTargets.Class, AllowMultiple = true)]
public class TagAttribute : Attribute
{
    public string Name { get; }
    public TagAttribute(string name) => Name = name;
}

[Tag("First")]
[Tag("Second")]
class Sample {}

class Program
{
    static void Main()
    {
        var attrs = Attribute.GetCustomAttributes(typeof(Sample), typeof(TagAttribute)).Cast<TagAttribute>();
        foreach(var attr in attrs)
            Console.WriteLine(attr.Name);
    }
}
ACompilation error due to multiple attributes
BFirst
CSecond\nFirst
DFirst\nSecond
Attempts:
2 left
💡 Hint
AllowMultiple = true allows multiple attributes of the same type on one target.
❓ Predict Output
advanced
2:00remaining
Attribute usage with invalid target
What error does this code produce when compiled?
C Sharp (C#)
using System;

[AttributeUsage(AttributeTargets.Method)]
public class TestAttribute : Attribute {}

[Test]
class Demo
{
    public void Run() {}
}
ACompilation error: Attribute 'Test' is not valid on class
BNo error, compiles successfully
CWarning but compiles
DRuntime error: Invalid attribute usage
Attempts:
2 left
💡 Hint
Check the AttributeTargets specified and where the attribute is applied.
🧠 Conceptual
expert
2:00remaining
Determining valid attribute targets
Given this attribute declaration, which of the following targets can it be applied to without error? [AttributeUsage(AttributeTargets.Field | AttributeTargets.Property | AttributeTargets.Parameter)] public class ValidateAttribute : Attribute {}
AOnly a property and a class
BA field, a property, and a method parameter
COnly a field and a method
DA method, a property, and a class
Attempts:
2 left
💡 Hint
Look carefully at the AttributeTargets flags used.

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