views:

64

answers:

4

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?

+2  A: 

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.

Ken Browning
A: 

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 :)

Ricky AH
+1  A: 

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.

Dean Johnston
+1  A: 

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

Bolek Tekielski