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

Reading attributes with reflection in C Sharp (C#) - Step-by-Step Execution

Choose your learning style9 modes available
Concept Flow - Reading attributes with reflection
Start: Define class with attribute
Create instance or get type
Use reflection to get Type info
Check for attribute presence
Read attribute properties
Use attribute data as needed
End
This flow shows how to define a class with an attribute, then use reflection to find and read that attribute's data at runtime.
Execution Sample
C Sharp (C#)
using System;

[Obsolete("Use NewClass instead")]
class OldClass {}

class Program {
    static void Main() {
        var type = typeof(OldClass);
        var attr = (ObsoleteAttribute)Attribute.GetCustomAttribute(type, typeof(ObsoleteAttribute));
        Console.WriteLine(attr.Message);
    }
}
This code reads the Obsolete attribute message from OldClass using reflection and prints it.
Execution Table
StepActionEvaluationResult
1Define class OldClass with Obsolete attributeClass OldClass has Obsolete attribute with message 'Use NewClass instead'Class ready with attribute
2Get Type object for OldClasstypeof(OldClass)Type object representing OldClass
3Call Attribute.GetCustomAttribute(type, ObsoleteAttribute)Search attributes on OldClass for ObsoleteAttributeObsoleteAttribute instance found
4Cast returned attribute to ObsoleteAttributeCast successObsoleteAttribute instance with Message property
5Access attr.Messageattr.Message"Use NewClass instead"
6Print attr.MessageConsole.WriteLine outputUse NewClass instead
💡 All steps completed, attribute message printed
Variable Tracker
VariableStartAfter Step 2After Step 3After Step 4After Step 5Final
typenullType(OldClass)Type(OldClass)Type(OldClass)Type(OldClass)Type(OldClass)
attrnullnullObsoleteAttribute instanceObsoleteAttribute instanceObsoleteAttribute instanceObsoleteAttribute instance
attr.MessageN/AN/AN/AN/A"Use NewClass instead""Use NewClass instead"
Key Moments - 3 Insights
Why do we cast the result of GetCustomAttribute to ObsoleteAttribute?
GetCustomAttribute returns a general Attribute object, so we cast it to ObsoleteAttribute to access its specific properties like Message, as shown in step 4 of the execution_table.
What happens if the attribute is not present on the class?
GetCustomAttribute returns null if the attribute is missing. This means attr would be null and accessing attr.Message would cause an error. This is why checking for null before use is important.
Why do we use typeof(OldClass) instead of creating an instance?
Reflection can get attribute info from the Type itself without needing an instance. This is shown in step 2 where typeof(OldClass) gets the Type object.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, what is the value of attr.Message at step 5?
A"OldClass is obsolete"
Bnull
C"Use NewClass instead"
DAn exception is thrown
💡 Hint
Check the 'Evaluation' column in row for step 5 in execution_table
At which step does the program find the ObsoleteAttribute on OldClass?
AStep 3
BStep 2
CStep 4
DStep 6
💡 Hint
Look at the 'Action' and 'Result' columns in execution_table rows
If OldClass had no Obsolete attribute, what would attr be after step 3?
AAn ObsoleteAttribute instance
Bnull
CA Type object
DAn exception is thrown
💡 Hint
Refer to key_moments explanation about missing attributes and GetCustomAttribute behavior
Concept Snapshot
Reading attributes with reflection in C#:
- Use typeof(ClassName) to get Type
- Use Attribute.GetCustomAttribute(Type, AttributeType) to get attribute
- Cast to specific attribute type to access properties
- Check for null to avoid errors if attribute missing
- Use attribute data as needed at runtime
Full Transcript
This example shows how to read attributes from a class using reflection in C#. First, a class OldClass is defined with the Obsolete attribute that has a message. Then, the program gets the Type object for OldClass using typeof. Next, it calls Attribute.GetCustomAttribute to find the Obsolete attribute on that class. The returned attribute is cast to ObsoleteAttribute so its Message property can be accessed. Finally, the message is printed to the console. The execution table traces each step, showing how variables change and what actions happen. Key moments clarify why casting is needed, what happens if the attribute is missing, and why typeof is used instead of creating an instance. The visual quiz tests understanding of attribute reading steps and results. This method allows programs to read metadata about classes at runtime and use it for various purposes.