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

Custom attribute classes in C Sharp (C#) - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Custom Attribute Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate
2:00remaining
What is the output of this code using a custom attribute?

Consider the following C# code that defines a custom attribute and uses it on a class. What will be printed when running the Main method?

C Sharp (C#)
using System;

[AttributeUsage(AttributeTargets.Class)]
public class InfoAttribute : Attribute
{
    public string Description { get; }
    public InfoAttribute(string description) => Description = description;
}

[Info("This is a sample class")]
public class SampleClass {}

public class Program
{
    public static void Main()
    {
        var attr = (InfoAttribute)Attribute.GetCustomAttribute(typeof(SampleClass), typeof(InfoAttribute));
        Console.WriteLine(attr.Description);
    }
}
ACompilation error
BSystem.InfoAttribute
Cnull
DThis is a sample class
Attempts:
2 left
💡 Hint

Look at how the attribute is retrieved and what property is printed.

🧠 Conceptual
intermediate
1:30remaining
Which attribute usage is valid for this custom attribute?

Given a custom attribute defined as below, which AttributeUsage setting correctly restricts it to be used only on methods?

C Sharp (C#)
using System;

[AttributeUsage(AttributeTargets.Method)]
public class MyMethodAttribute : Attribute
{
}
A[AttributeUsage(AttributeTargets.Method)]
B[AttributeUsage(AttributeTargets.Class)]
C[AttributeUsage(AttributeTargets.Property)]
D[AttributeUsage(AttributeTargets.Field)]
Attempts:
2 left
💡 Hint

Think about which AttributeTargets value limits usage to methods only.

🔧 Debug
advanced
2:30remaining
Why does this code throw an exception when retrieving the attribute?

Examine the code below. It throws a NullReferenceException at runtime. What is the cause?

C Sharp (C#)
using System;

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

public class Product {}

public class Program
{
    public static void Main()
    {
        var attr = (TagAttribute)Attribute.GetCustomAttribute(typeof(Product), typeof(TagAttribute));
        Console.WriteLine(attr.Name.ToUpper());
    }
}
AThe Product class does not have the TagAttribute applied, so attr is null causing NullReferenceException.
BThe TagAttribute constructor is missing a parameterless constructor causing the error.
CAttributeUsage is set incorrectly causing the attribute not to be found.
DThe cast to TagAttribute is invalid causing an InvalidCastException.
Attempts:
2 left
💡 Hint

Check if the attribute is actually applied to the class before retrieving it.

📝 Syntax
advanced
2:00remaining
Which option correctly defines a custom attribute with a named property?

Which of the following code snippets correctly defines a custom attribute with a named property Version that can be set optionally?

Apublic class VersionAttribute : Attribute { public int Version; }
Bpublic class VersionAttribute : Attribute { public int Version { get; set; } }
Cpublic class VersionAttribute : Attribute { public int Version() { get; set; } }
Dpublic class VersionAttribute : Attribute { public int GetVersion() => 1; }
Attempts:
2 left
💡 Hint

Remember named properties in attributes must be public properties with get and set accessors.

🚀 Application
expert
3:00remaining
What is the output of this code using multiple custom attributes and reflection?

Given the code below, what will be printed when running the Main method?

C Sharp (C#)
using System;
using System.Reflection;

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

[Tag("Utility")]
[Tag("Core")]
public class Helper {}

public class Program
{
    public static void Main()
    {
        var attrs = (TagAttribute[])Attribute.GetCustomAttributes(typeof(Helper), typeof(TagAttribute));
        foreach (var attr in attrs)
            Console.Write(attr.Name + " ");
    }
}
ACompilation error due to multiple attributes
BCore Utility
CUtility Core
DUtilityCore
Attempts:
2 left
💡 Hint

Check the order attributes are declared and how they are retrieved.

Practice

(1/5)
1. What is the main purpose of creating a custom attribute class in C#?
easy
A. To create a new data type for variables
B. To replace the main class in a program
C. To add extra information to code elements like classes or methods
D. To handle exceptions automatically

Solution

  1. Step 1: Understand what attributes do

    Attributes add metadata, or extra info, to code elements like classes or methods.
  2. Step 2: Identify the role of custom attributes

    Custom attributes let you define your own extra info to attach to code elements.
  3. Final Answer:

    To add extra information to code elements like classes or methods -> Option C
  4. Quick Check:

    Custom attributes = extra info [OK]
Hint: Attributes add info to code elements, not change logic [OK]
Common Mistakes:
  • Thinking attributes replace classes
  • Confusing attributes with data types
  • Assuming attributes handle errors
2. Which of the following is the correct way to declare a custom attribute class named InfoAttribute?
easy
A. public struct InfoAttribute : Attribute {}
B. public attribute InfoAttribute {}
C. public class InfoAttribute extends Attribute {}
D. public class InfoAttribute : System.Attribute {}

Solution

  1. Step 1: Recall C# syntax for custom attributes

    Custom attribute classes must inherit from System.Attribute using a class declaration.
  2. Step 2: Check each option

    public class InfoAttribute : System.Attribute {} correctly uses 'public class InfoAttribute : System.Attribute {}'. public attribute InfoAttribute {} uses invalid keyword 'attribute'. public class InfoAttribute extends Attribute {} uses 'extends' which is Java syntax. public struct InfoAttribute : Attribute {} uses 'struct' which is not correct for attributes.
  3. Final Answer:

    public class InfoAttribute : System.Attribute {} -> Option D
  4. Quick Check:

    Custom attribute = class + : System.Attribute [OK]
Hint: Custom attributes are classes inheriting System.Attribute [OK]
Common Mistakes:
  • Using 'attribute' keyword instead of 'class'
  • Using Java syntax 'extends' instead of ':'
  • Declaring attribute as struct
3. What will be the output of the following code?
using System;
[Info("Version 1.0")]
class Program {}

public class InfoAttribute : Attribute
{
    public string Version { get; }
    public InfoAttribute(string version) => Version = version;
}

class Test
{
    static void Main()
    {
        var attrs = typeof(Program).GetCustomAttributes(typeof(InfoAttribute), false);
        if (attrs.Length > 0)
            Console.WriteLine(((InfoAttribute)attrs[0]).Version);
        else
            Console.WriteLine("No attribute");
    }
}
medium
A. Version 1.0
B. No attribute
C. Compilation error
D. Runtime exception

Solution

  1. Step 1: Understand attribute application

    The Program class has the Info attribute with version "Version 1.0" applied.
  2. Step 2: Check reflection code

    The code uses reflection to get InfoAttribute from Program. Since it exists, it prints the Version property.
  3. Final Answer:

    Version 1.0 -> Option A
  4. Quick Check:

    Reflection finds attribute version = Version 1.0 [OK]
Hint: Reflection reads attribute properties if applied [OK]
Common Mistakes:
  • Assuming attribute is not found
  • Confusing attribute class with target class
  • Forgetting to cast attribute before accessing property
4. Identify the error in this custom attribute declaration:
public class MyAttribute
{
    public string Name { get; set; }
    public MyAttribute(string name) { Name = name; }
}
medium
A. Missing inheritance from System.Attribute
B. Property Name should be private
C. Constructor should not have parameters
D. Class should be declared as struct

Solution

  1. Step 1: Check inheritance requirement

    Custom attribute classes must inherit from System.Attribute to be recognized as attributes.
  2. Step 2: Analyze given code

    The class MyAttribute does not inherit from System.Attribute, so it is not a valid attribute class.
  3. Final Answer:

    Missing inheritance from System.Attribute -> Option A
  4. Quick Check:

    Attributes must inherit System.Attribute [OK]
Hint: Always inherit System.Attribute for custom attributes [OK]
Common Mistakes:
  • Forgetting to inherit System.Attribute
  • Thinking constructor must be parameterless
  • Using struct instead of class
5. You want to create a custom attribute PriorityAttribute that accepts an integer priority level and can be applied only to methods. Which of the following is the correct way to declare it?
hard
A. [AttributeUsage(AttributeTargets.Class)] public class PriorityAttribute : Attribute { public int Level; public PriorityAttribute(int level) { Level = level; } }
B. [AttributeUsage(AttributeTargets.Method)] public class PriorityAttribute : Attribute { public int Level { get; } public PriorityAttribute(int level) => Level = level; }
C. public class PriorityAttribute : Attribute { public int Level { get; set; } public PriorityAttribute() {} }
D. [AttributeUsage(AttributeTargets.Method | AttributeTargets.Class)] public struct PriorityAttribute { public int Level; public PriorityAttribute(int level) { Level = level; } }

Solution

  1. Step 1: Check AttributeUsage target

    The attribute should apply only to methods, so AttributeTargets.Method is correct.
  2. Step 2: Verify class declaration and constructor

    It must be a class inheriting Attribute, with a constructor accepting an int and a read-only property.
  3. Step 3: Review options

    [AttributeUsage(AttributeTargets.Method)] public class PriorityAttribute : Attribute { public int Level { get; } public PriorityAttribute(int level) => Level = level; } matches all requirements. [AttributeUsage(AttributeTargets.Class)] public class PriorityAttribute : Attribute { public int Level; public PriorityAttribute(int level) { Level = level; } } targets classes, not methods. public class PriorityAttribute : Attribute { public int Level { get; set; } public PriorityAttribute() {} } lacks constructor parameter and target restriction. [AttributeUsage(AttributeTargets.Method | AttributeTargets.Class)] public struct PriorityAttribute { public int Level; public PriorityAttribute(int level) { Level = level; } } uses struct, which is invalid for attributes.
  4. Final Answer:

    [AttributeUsage(AttributeTargets.Method)] public class PriorityAttribute : Attribute { public int Level { get; } public PriorityAttribute(int level) => Level = level; } -> Option B
  5. Quick Check:

    AttributeUsage + class + constructor with param = [AttributeUsage(AttributeTargets.Method)] public class PriorityAttribute : Attribute { public int Level { get; } public PriorityAttribute(int level) => Level = level; } [OK]
Hint: Use AttributeUsage to limit targets and inherit Attribute [OK]
Common Mistakes:
  • Using struct instead of class
  • Wrong AttributeTargets in AttributeUsage
  • Missing constructor parameter for priority
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