xraminx
xraminx

Reputation: 1176

Execute some specific code before member functions of a class using attributes?

I have a class:

public class MyClass
{
  public int code { set; get; }
  public bool foo()
  {
    // do some stuff
    // ...
    code = 100;
    return true;
  }

  public bool bar()
  {
    // do some stuff
    // ...
    code = 200;
    return true;
  }

  // more methods ...
  // ...
}

I would like to reset the value of code to zero at the beginning of each member function call. Of course I can manually set the value to zero at the beginning of each function but I am wondering if it is possible to use attributes for this purpose:

[ResetTheCode]
public bool bar()
{
  // do some stuff
  // ...
  code = 200;
  return true;
}

Something similar to action filters in ASP.NET MVC. Is this possible?

Upvotes: 2

Views: 640

Answers (4)

Kent Boogaart
Kent Boogaart

Reputation: 178680

An AOP framework will allow you to do this. Castle Windsor, for example.

Upvotes: 2

Robert Kozak
Robert Kozak

Reputation: 2033

Attributes in and of themselves don't do anything except work like a marker or metadata to your code. You would have to write some reflection code to get the attribute and do something with it.

An AOP framework like PostSharp, Castle Windsor, and others does the work of evaluating Attributes based upon the rules of its framework.

Upvotes: 0

Andrew Hare
Andrew Hare

Reputation: 351526

You could definitely do something like this with an AOP framework (like PostSharp) but don't you think that would be quite confusing to anyone unfamiliar with your process?

This is one of those things that even though you can do it doesn't necessarily mean you should. The time and effort taken to type the attribute name above the method cannot possibly be less than the time and effort needed to write the reset code (which should be in its own method as well so you don't copy/paste a magic number everywhere).

Upvotes: 1

Razzie
Razzie

Reputation: 31222

Agreed with Kent. In addition, take a look at PostSharp, which is also a very mature .NET AOP framework.

Upvotes: 3

Related Questions