Skip to Content
Course content
Click on the "Edit" button in the top corner of the screen to edit your slide content.

I've noticed a recurring pattern when developers first encounter attributes. They see things like [Serializable] or [HttpPost] in ASP.NET and assume that the attribute itself is "doing" the work. There's a common belief that placing a custom attribute above a method acts like a trigger or a hook—that the attribute contains logic that automatically intercepts the execution of that method.

Attributes Aren't Magic Triggers

If you think that adding [LogExecution] to a method will suddenly make that method print its own logs to the console, you're in for a surprise. Let's look at why that's wrong. If I write this:

[LogExecution]
public void ProcessPayment() 
{
    // Payment logic here
}

Absolutely nothing happens. The LogExecutionAttribute class can have methods and properties, but C# never automatically calls them just because the attribute is present. If you've used frameworks like Spring in Java or certain AOP (Aspect Oriented Programming) libraries, you might be used to "magic" intercepts, but in raw C#, attributes are passive. They are just data.

Metadata is Just a Sticker

The correct way to think about attributes is as "stickers" or "tags." When you apply an attribute, you aren't adding behavior; you are adding metadata. You're essentially leaving a note for some other piece of code to find later.

To make an attribute actually do something, you need a "Processor"—a piece of code that uses Reflection to look at the tags and decide how to react. Here is how you actually build this pattern. First, you define the attribute by inheriting from System.Attribute:

[AttributeUsage(AttributeTargets.Method)]
public class DeveloperNoteAttribute : Attribute
{
    public string Note { get; }
    public DeveloperNoteAttribute(string note)
    {
        Note = note;
    }
}

Now, I can tag several methods in my codebase with specific warnings or notes. But remember: these notes are invisible to the program's actual logic until we go looking for them.

Putting the Processor to Work

To make the metadata useful, you need to write the logic that reads the attribute. This usually happens at startup or via a wrapper. I like to think of this as the "Scanner" phase. Here is a simple example of a processor that scans a class for those DeveloperNote stickers and prints them out:

public class NoteProcessor
{
    public void PrintNotes(object obj)
    {
        var type = obj.GetType();
        var methods = type.GetMethods();

        foreach (var method in methods)
        {
            var noteAttr = (DeveloperNoteAttribute)Attribute.GetCustomAttribute(method, typeof(DeveloperNoteAttribute));
            
            if (noteAttr != null)
            {
                Console.WriteLine($"Method {method.Name} has a note: {noteAttr.Note}");
            }
        }
    }
}

I'll be honest: you won't write "Processors" every day. Most of the time, you'll be using attributes provided by a framework (like Entity Framework or Newtonsoft.Json) where the framework authors have already written the complex Reflection logic for you. But understanding that the attribute is just a label and the framework is the reader is the key to mastering how C# handles metadata.




📋 Practical Task

Building a Method Permission Validator

Your goal is to create a simple permission system using custom attributes. Instead of hard-coding permission checks inside every method, you will tag methods with a required role and create a validator that checks if a user has that role before "allowing" the method to run.

  • Create a custom attribute called RequiredRoleAttribute that takes a string (the role name) in its constructor.
  • Create a class SecureService with at least two methods: one tagged with [RequiredRole("Admin")] and another tagged with [RequiredRole("User")].
  • Create a PermissionChecker class with a method bool CanExecute(object userRole, string methodName, object serviceInstance).
  • The CanExecute method must use Reflection to:
    1. Find the method by name on the service instance.
    2. Check if the RequiredRoleAttribute is present.
    3. Compare the role defined in the attribute with the userRole provided.
    4. Return true if the roles match or if no attribute is present; otherwise, return false.
Rating
0 0

There are no comments for now.

to be the first to leave a comment.