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

Reading attributes with reflection in C Sharp (C#) - Mini Project: Build & Apply

Choose your learning style9 modes available
Reading attributes with reflection
📖 Scenario: Imagine you have a simple program where you want to label some classes with extra information using attributes. Later, you want to read these labels to decide what to do.
🎯 Goal: You will create a custom attribute, apply it to a class, and then use reflection to read and display the attribute's value.
📋 What You'll Learn
Create a custom attribute class called InfoAttribute with a string property Description.
Create a class called Product and apply the InfoAttribute with the description "This is a product class".
Use reflection to get the InfoAttribute from the Product class.
Print the Description value of the InfoAttribute.
💡 Why This Matters
🌍 Real World
Attributes let you add extra information to your code that can be read later. This is useful for marking classes with metadata, like marking which classes need special handling.
💼 Career
Many C# jobs require understanding attributes and reflection to work with frameworks, libraries, or custom tools that use metadata for configuration or behavior.
Progress0 / 4 steps
1
Create the custom attribute class
Create a public class called InfoAttribute that inherits from System.Attribute. Add a public string property called Description with a getter and setter.
C Sharp (C#)
Need a hint?

Remember, custom attributes inherit from System.Attribute. Use a public property to hold the description.

2
Create the Product class with the attribute
Create a public class called Product. Apply the InfoAttribute to it with the description set to "This is a product class".
C Sharp (C#)
Need a hint?

Use square brackets [] to apply the attribute above the class. Set the Description property inside the attribute.

3
Use reflection to read the attribute
Write code to get the InfoAttribute from the Product class using reflection. Store the attribute in a variable called infoAttr.
C Sharp (C#)
Need a hint?

Use typeof(Product) to get the type. Use Attribute.GetCustomAttribute to get the attribute.

4
Print the attribute description
Add a Console.WriteLine statement to print the Description property of infoAttr.
C Sharp (C#)
Need a hint?

Use Console.WriteLine(infoAttr.Description); to print the description.