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

Attribute targets and usage in C Sharp (C#) - Mini Project: Build & Apply

Choose your learning style9 modes available
Attribute Targets and Usage in C#
📖 Scenario: You are creating a simple C# program to understand how to apply attributes to different parts of your code, like classes, methods, and properties. Attributes add extra information to your code that can be used by the compiler or at runtime.
🎯 Goal: Build a C# program that defines a custom attribute and applies it to a class, a method, and a property using correct attribute targets.
📋 What You'll Learn
Create a custom attribute class named InfoAttribute.
Apply InfoAttribute to a class, a method, and a property using correct attribute targets.
Use the AttributeUsage attribute to specify valid targets for InfoAttribute.
Print messages to confirm the attribute usage.
💡 Why This Matters
🌍 Real World
Attributes are used in real-world C# programs to add metadata for tools, frameworks, and runtime behaviors, like marking methods for testing or serialization.
💼 Career
Understanding attributes is important for working with many C# frameworks and libraries, such as ASP.NET, Entity Framework, and unit testing tools.
Progress0 / 4 steps
1
Create the custom attribute class
Create a public class called InfoAttribute that inherits from System.Attribute. Inside it, add a public string property called Description with a constructor that sets this property.
C Sharp (C#)
Need a hint?

Remember, custom attributes inherit from System.Attribute. Use a constructor to set the description.

2
Specify attribute usage targets
Add the AttributeUsage attribute above the InfoAttribute class to allow it to be used on Class, Method, and Property targets.
C Sharp (C#)
Need a hint?

Use AttributeTargets.Class, AttributeTargets.Method, and AttributeTargets.Property combined with the bitwise OR operator |.

3
Apply the attribute to class, method, and property
Create a public class called Product. Apply [Info("Class for product details")] to the class. Inside, add a public property Name of type string with [Info("Product name")] attribute. Also add a public method Display with [Info("Display product info")] attribute that prints the product name.
C Sharp (C#)
Need a hint?

Apply the [Info(...)] attribute above the class, property, and method declarations.

4
Create instance and call method to show attribute usage
In the Main method, create an instance of Product, set its Name to "Laptop", and call the Display method to print the product name.
C Sharp (C#)
Need a hint?

Create a Product object, set the Name property, then call Display() to print the name.