Applying a custom attribute Tested(name, testgrade): which applications are correct for assembly-level and class-level usage?

Difficulty: Easy

Correct Answer: [assembly: Tested('Sachin', testgrade.Good)] and [Tested('Virat', testgrade.Excellent)] class Customer { /.../ } are both valid usages

Explanation:

Introduction / Context:Custom attributes in C# are user-defined classes derived from System.Attribute. Once created, they can be applied to a variety of targets, including assemblies and classes, provided their AttributeUsage allows those targets.

Given Data / Assumptions:

  • The custom attribute is named Tested and takes two arguments: a tester's name and a testgrade enum value.
  • Two example applications are shown: one at assembly level and one at class level.
  • There are also claims that attributes cannot be applied to assemblies or classes/methods.

Concept / Approach:Assembly-level attributes use the special target specifier inside the brackets: [assembly: …]. Class-level attributes are placed directly above the class declaration. Both are standard and valid, assuming AttributeUsage supports those targets.

Step-by-Step Solution:

Check assembly-level usage → [assembly: Tested(""..."", testgrade.Good)] is valid.Check class-level usage → [Tested(""..."" , testgrade.Excellent)] before a class is valid.Claims that attributes cannot be applied to assembly/class/method are false in general C#.

Verification / Alternative check:Create a minimal TestedAttribute : Attribute class with [AttributeUsage(AttributeTargets.Assembly | AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = true)], apply at assembly and class scope, and compile successfully.

Why Other Options Are Wrong:They assert impossibilities (e.g., cannot apply to assemblies or classes) that contradict the attribute system.

Common Pitfalls:Forgetting the assembly target specifier; assuming attributes default to all targets without AttributeUsage configuration.

Final Answer:[assembly: Tested('Sachin', testgrade.Good)] and [Tested('Virat', testgrade.Excellent)] class Customer { /.../ } are both valid usages

Discussion & Comments

No comments yet. Be the first to comment!
Join Discussion