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

Custom attribute classes in C Sharp (C#) - Step-by-Step Execution

Choose your learning style9 modes available
Concept Flow - Custom attribute classes
Define attribute class
Apply attribute to target
Run program
Use reflection to read attribute
Access attribute data
Use data in program
First, you create a custom attribute class. Then you put it on something like a class or method. When the program runs, you read that attribute using reflection to get its data.
Execution Sample
C Sharp (C#)
using System;

[AttributeUsage(AttributeTargets.Class)]
class MyInfoAttribute : Attribute {
  public string Info { get; }
  public MyInfoAttribute(string info) => Info = info;
}

[MyInfo("Hello World")]
class MyClass {}

class Program {
  static void Main() {
    var attr = (MyInfoAttribute)Attribute.GetCustomAttribute(typeof(MyClass), typeof(MyInfoAttribute));
    Console.WriteLine(attr.Info);
  }
}
This code defines a custom attribute with a string, applies it to a class, then reads and prints the string at runtime.
Execution Table
StepActionEvaluationResult
1Define MyInfoAttribute classClass createdReady to use attribute
2Apply [MyInfo("Hello World")] to MyClassAttribute attached to MyClassMyClass has attribute data
3Start Main methodProgram runsReady to get attribute
4Call Attribute.GetCustomAttribute for MyClassFind MyInfoAttribute on MyClassReturns MyInfoAttribute instance
5Access attr.InfoGet string value"Hello World"
6Print attr.InfoOutput to consoleHello World
7Program endsNo more codeExecution stops
💡 Program ends after printing the attribute's Info string
Variable Tracker
VariableStartAfter Step 4After Step 5Final
attrnullMyInfoAttribute instanceMyInfoAttribute instanceMyInfoAttribute instance
attr.InfoN/AN/A"Hello World""Hello World"
Key Moments - 3 Insights
Why do we cast the result of GetCustomAttribute to MyInfoAttribute?
GetCustomAttribute returns a general Attribute object, so we cast it to MyInfoAttribute to access the Info property, as shown in step 4 of the execution_table.
What happens if the attribute is not found on the class?
GetCustomAttribute returns null, so attr would be null and accessing attr.Info would cause an error. This is why checking for null is important in real code.
Why do we use [AttributeUsage(AttributeTargets.Class)] on the attribute class?
This limits the attribute to be used only on classes, preventing misuse on other targets like methods or properties.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, what is the value of attr.Info at step 5?
Anull
B"Hello World"
CAn error
D"MyClass"
💡 Hint
Check the 'Evaluation' and 'Result' columns at step 5 in the execution_table.
At which step does the program find the attribute instance on MyClass?
AStep 4
BStep 6
CStep 3
DStep 2
💡 Hint
Look for when Attribute.GetCustomAttribute is called in the execution_table.
If we remove [AttributeUsage(AttributeTargets.Class)], what might happen?
AThe attribute will not be found at runtime.
BThe program will not compile.
CThe attribute can be applied to any target, not just classes.
DThe Info property will be empty.
💡 Hint
Refer to the key_moments explanation about AttributeUsage.
Concept Snapshot
Custom attribute classes let you add extra info to code elements.
Define a class inheriting Attribute.
Use [AttributeUsage] to limit targets.
Apply with [YourAttribute(...)] syntax.
Read at runtime with reflection (GetCustomAttribute).
Access your data from the attribute instance.
Full Transcript
This lesson shows how to create and use custom attribute classes in C#. First, you define a class that inherits from Attribute and add any properties you want. Then you apply this attribute to a class using square brackets. When the program runs, you use reflection to get the attribute instance from the class and read its data. The example prints the string stored in the attribute. Key points include casting the attribute to your custom type and using AttributeUsage to control where the attribute can be applied.