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