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

Attribute declaration syntax in C Sharp (C#) - Mini Project: Build & Apply

Choose your learning style9 modes available
Attribute declaration syntax
📖 Scenario: You are creating a simple program to mark classes and methods with custom notes using attributes. Attributes are special tags that add extra information to your code, like labels on a box.
🎯 Goal: Learn how to declare and use attributes in C# by creating a custom attribute and applying it to a class and a method.
📋 What You'll Learn
Declare a custom attribute class called InfoAttribute with a string property Description.
Create a class called Calculator and apply the InfoAttribute with a description.
Add a method Add inside Calculator and apply the InfoAttribute with a description.
Print the descriptions stored in the attributes for the class and method.
💡 Why This Matters
🌍 Real World
Attributes are used in real-world C# programs to add metadata for tools, frameworks, and libraries. For example, marking methods as test cases or marking classes for serialization.
💼 Career
Understanding attribute declaration and usage is important for C# developers working with frameworks like ASP.NET, Entity Framework, or writing reusable libraries.
Progress0 / 4 steps
1
Declare the InfoAttribute class
Declare 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, attributes in C# inherit from System.Attribute. Use public string Description { get; set; } to create the property.

2
Create the Calculator class and apply InfoAttribute
Create a public class called Calculator. Apply the InfoAttribute to it with the description set to "Performs basic math operations".
C Sharp (C#)
Need a hint?

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

3
Add Add method with InfoAttribute
Inside the Calculator class, add a public method called Add that takes two integers a and b and returns their sum. Apply the InfoAttribute to this method with the description "Adds two numbers".
C Sharp (C#)
Need a hint?

Apply the attribute above the method. The method should return the sum of a and b.

4
Print attribute descriptions for class and method
Write code in Main to get the InfoAttribute from the Calculator class and its Add method. Print the Description property of both attributes.
C Sharp (C#)
Need a hint?

Use Attribute.GetCustomAttribute to get the attribute from the class and method. Then print their Description.