tags:

views:

104

answers:

4

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?

+2  A: 

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

HTH, Kent

Kent Boogaart
+3  A: 

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

Razzie
+1  A: 

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

Andrew Hare
A: 

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.

Robert Kozak