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

Reading attributes with reflection in C Sharp (C#) - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Reflection Attribute Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate
2:00remaining
Output of reading a custom attribute on a class
What is the output of this C# program that reads a custom attribute from a class using reflection?
C Sharp (C#)
using System;

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

[Info("Sample class for testing")]
public class SampleClass {}

public class Program
{
    public static void Main()
    {
        var type = typeof(SampleClass);
        var attr = (InfoAttribute)Attribute.GetCustomAttribute(type, typeof(InfoAttribute));
        Console.WriteLine(attr?.Description ?? "No attribute found");
    }
}
ASample class for testing
BNo attribute found
CSystem.InfoAttribute
DCompilation error
Attempts:
2 left
💡 Hint
Look at how the attribute is applied and how reflection retrieves it.
❓ Predict Output
intermediate
2:00remaining
Output when attribute is missing
What will be the output when trying to read a custom attribute that is not applied to the class?
C Sharp (C#)
using System;

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

public class NoAttributeClass {}

public class Program
{
    public static void Main()
    {
        var type = typeof(NoAttributeClass);
        var attr = (InfoAttribute)Attribute.GetCustomAttribute(type, typeof(InfoAttribute));
        Console.WriteLine(attr?.Description ?? "No attribute found");
    }
}
AEmpty line
Bnull
CNo attribute found
DCompilation error
Attempts:
2 left
💡 Hint
Check what happens when the attribute is not present and null is returned.
🔧 Debug
advanced
2:30remaining
Identify the error when reading multiple attributes
This code tries to read multiple custom attributes from a class but throws an exception. What is the cause?
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("alpha")]
[Tag("beta")]
public class MultiTagClass {}

public class Program
{
    public static void Main()
    {
        var type = typeof(MultiTagClass);
        var attr = (TagAttribute)Attribute.GetCustomAttributes(type, typeof(TagAttribute));
        Console.WriteLine(attr.Name);
    }
}
AInvalid cast exception because GetCustomAttributes returns an array
BOutputs 'alpha'
CCompilation error due to missing using directive
DNullReferenceException because no attribute found
Attempts:
2 left
💡 Hint
Check the return type of GetCustomAttributes when multiple attributes are allowed.
📝 Syntax
advanced
2:30remaining
Correct syntax to read all attributes of a type
Which option correctly reads all custom attributes of type TagAttribute applied to a class?
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("one")]
[Tag("two")]
public class TestClass {}

public class Program
{
    public static void Main()
    {
        var type = typeof(TestClass);
        // Which option correctly reads all TagAttribute instances?
    }
}
Avar attrs = Attribute.GetCustomAttribute(type, typeof(TagAttribute));
Bvar attrs = (TagAttribute)Attribute.GetCustomAttributes(type, typeof(TagAttribute));
Cvar attrs = type.GetCustomAttribute(typeof(TagAttribute));
Dvar attrs = (TagAttribute[])Attribute.GetCustomAttributes(type, typeof(TagAttribute));
Attempts:
2 left
💡 Hint
GetCustomAttributes returns an array of attributes, not a single attribute.
🚀 Application
expert
3:00remaining
Count how many properties have a specific attribute
Given a class with properties decorated with a custom attribute, what is the value of count after running this code?
C Sharp (C#)
using System;
using System.Reflection;

[AttributeUsage(AttributeTargets.Property)]
public class ImportantAttribute : Attribute {}

public class Data
{
    [Important]
    public int Id { get; set; }

    public string Name { get; set; }

    [Important]
    public double Value { get; set; }
}

public class Program
{
    public static void Main()
    {
        var type = typeof(Data);
        int count = 0;
        foreach (var prop in type.GetProperties())
        {
            if (Attribute.IsDefined(prop, typeof(ImportantAttribute)))
                count++;
        }
        Console.WriteLine(count);
    }
}
A3
B2
C1
D0
Attempts:
2 left
💡 Hint
Count only properties with the ImportantAttribute applied.

Practice

(1/5)
1. What does reading attributes with reflection in C# allow you to do?
easy
A. Access extra information added to classes or methods at runtime
B. Change the source code of a program while it runs
C. Compile code faster by skipping attribute checks
D. Automatically generate user interfaces without coding

Solution

  1. Step 1: Understand what attributes are

    Attributes are extra notes or metadata added to code elements like classes or methods.
  2. Step 2: Understand reflection's role

    Reflection lets you look at these attributes while the program runs, to read their information.
  3. Final Answer:

    Access extra information added to classes or methods at runtime -> Option A
  4. Quick Check:

    Reflection reads attributes = Access extra info [OK]
Hint: Reflection reads metadata added to code elements [OK]
Common Mistakes:
  • Thinking reflection changes code instead of reading it
  • Confusing attributes with variables or methods
  • Believing attributes speed up compilation
2. Which of the following is the correct way to get custom attributes of a class using reflection in C#?
easy
A. GetAttributes(typeof(MyClass))
B. typeof(MyClass).GetCustomAttributes()
C. MyClass.GetAttributes()
D. MyClass.Attributes()

Solution

  1. Step 1: Recall the reflection syntax for attributes

    In C#, to get attributes of a class, use typeof(ClassName).GetCustomAttributes().
  2. Step 2: Check each option

    Only typeof(MyClass).GetCustomAttributes() uses the correct syntax with typeof and GetCustomAttributes method.
  3. Final Answer:

    typeof(MyClass).GetCustomAttributes() -> Option B
  4. Quick Check:

    Correct syntax uses typeof and GetCustomAttributes() [OK]
Hint: Use typeof(Class).GetCustomAttributes() to read attributes [OK]
Common Mistakes:
  • Calling GetAttributes() directly on class name
  • Using instance methods instead of typeof
  • Confusing method names like Attributes()
3. Given this code snippet, what will be the output?
[System.Obsolete("Use NewMethod instead")]
class OldClass {}

var attrs = typeof(OldClass).GetCustomAttributes(typeof(System.ObsoleteAttribute), false);
Console.WriteLine(attrs.Length);
medium
A. 0
B. null
C. Throws an exception
D. 1

Solution

  1. Step 1: Identify the attribute applied

    The class OldClass has the Obsolete attribute applied once.
  2. Step 2: Check GetCustomAttributes call

    GetCustomAttributes is called with ObsoleteAttribute type, so it returns an array with that attribute instance.
  3. Final Answer:

    1 -> Option D
  4. Quick Check:

    One Obsolete attribute found = 1 [OK]
Hint: Count attributes returned by GetCustomAttributes to find output length [OK]
Common Mistakes:
  • Assuming zero because attribute is ignored
  • Expecting null instead of empty array
  • Thinking it throws exception without reason
4. What is wrong with this code snippet that tries to read attributes?
class MyClass {}

var attrs = MyClass.GetCustomAttributes();
Console.WriteLine(attrs.Length);
medium
A. MyClass does not have any attributes
B. Console.WriteLine cannot print Length property
C. GetCustomAttributes is not a method of the class itself
D. Missing semicolon after class declaration

Solution

  1. Step 1: Check method call on class

    GetCustomAttributes is a method of Type, not the class itself, so calling MyClass.GetCustomAttributes() is invalid.
  2. Step 2: Correct usage

    You must use typeof(MyClass).GetCustomAttributes() to get attributes via reflection.
  3. Final Answer:

    GetCustomAttributes is not a method of the class itself -> Option C
  4. Quick Check:

    Use typeof(Class).GetCustomAttributes() not Class.GetCustomAttributes() [OK]
Hint: Call GetCustomAttributes on typeof(Class), not class name [OK]
Common Mistakes:
  • Calling GetCustomAttributes directly on class name
  • Ignoring that GetCustomAttributes is a Type method
  • Assuming attributes exist without checking
5. You want to read a custom attribute InfoAttribute applied to multiple methods in a class and print their descriptions. Which approach correctly reads and prints these descriptions?
hard
A. Use reflection to get MethodInfo array, then for each method call GetCustomAttributes(typeof(InfoAttribute), false) and print the Description property
B. Call GetCustomAttributes on the class type directly and print Description from the first attribute found
C. Use a foreach loop on class fields and call GetCustomAttributes on each field
D. Use reflection to get properties of the class and print their names

Solution

  1. Step 1: Identify target elements

    The attribute InfoAttribute is applied to methods, so we must get methods via reflection.
  2. Step 2: Read attributes per method

    For each MethodInfo, call GetCustomAttributes with InfoAttribute type to get the attribute instance and access its Description property.
  3. Step 3: Print descriptions

    Print the Description property for each method's attribute found.
  4. Final Answer:

    Use reflection to get MethodInfo array, then for each method call GetCustomAttributes(typeof(InfoAttribute), false) and print the Description property -> Option A
  5. Quick Check:

    Read attributes per method, not class or fields [OK]
Hint: Get methods, then read attributes on each method [OK]
Common Mistakes:
  • Reading attributes only on class instead of methods
  • Checking fields instead of methods
  • Assuming one attribute for whole class
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