The Matt
The Matt

Reputation: 6636

Possible to create an attribute that gets evaluated after instead of before?

I'm aware of writing custom attributes that decorate a method and get evaluated before the method executes, but is there a way to modify it so the attribute gets evaluated after the method gets executed?

Theoretically (in pseudo-code):

public void MyMethod()
{
     Console.WriteLine("Hello World");
}
[AttributeToExecuteAfter]

Am I misusing the concept of an attribute? If there's a technical reason this shouldn't be possible, what is it?

Upvotes: 1

Views: 382

Answers (4)

Bolek Tekielski
Bolek Tekielski

Reputation: 1214

Using PostSharp you can create custom handlers for entering and exiting decorated method.

Upvotes: 1

Dean Johnston
Dean Johnston

Reputation: 446

Are you referring to ActionFilters in .net MVC?

If you are, you can override the OnActionExecuted method by extending the abstract ActionFilterAttribute class. These only apply to mvc action methods though.

Upvotes: 1

Ken Browning
Ken Browning

Reputation: 29091

I think you are misunderstanding, yes. An attribute isn't code which runs before or after your method is run. An attribute is a piece of metadata attached to the method (or class, etc). Using reflection, code can be written to read that metadata.

Here's the best example I can think of:

The business object framework I use has the concept of a DataPortal. In an n-tier environment, the DataPortal sits on the server and executes my business objects' CRUD methods. The DataPortal was written in such a way that before calling my any of my CRUD methods, it first looks to see if the method has a RunMeInATransaction attribute on it. If it does, it creates a transaction, runs the method and then commits the transaction. Conceptually, it's a lot like methods having properties; my methods can have RunMeInATransaction property.

Upvotes: 1

Ricardo Amores
Ricardo Amores

Reputation: 4687

As Ken said, an attribute is just metadata attached to a method / property / field / class, useful to "tag" elements and then be able to recognize it with your code using reflection.

I.e, attributes are used in Linq2Sql as a way of mapping classes with database tables.

Your misunderstanding probably came from the fact that the C# compiler actually uses some special attributes to perform concrete operations. But that kind of functionality is not available for us, human developers :)

Upvotes: 0

Related Questions