Brian David Berman
Brian David Berman

Reputation: 7684

Is there a way to apply an attribute to a method that executes first?

Without using a library like PostSharp, is there a way to set up a custom attribute that I can have logic in that when attached to a method, will execute PRIOR to entering that method?

Upvotes: 3

Views: 143

Answers (1)

Marc Gravell
Marc Gravell

Reputation: 1062915

No; attributed are not intended to inject code. Tools like postsharp get around that with smoke and mirrors, but without that: no. Another option might be a decorator pattern, perhaps dynamically implementing an interface (not trivial by any means). However, adding a utility method-call to the top of the method(s) is much simpler, and presumably fine since if you have access to add attributes you have access to add a method-call.

Or put another way: tools like postsharp exist precicely because this doesn't exist out-of-the-box.

// poor man's aspect oriented programming
public void Foo() {
    SomeUtility.DoSomething();
    // real code
}

In some cases, subclassing may be useful, especially if the subclass is done at runtime (meta-programming):

class YouWriteThisAtRuntimeWithTypeBuilder : YourType {
    public override void Foo() {
        SomeUtility.DoSomething();
        base.Foo();
    }
}

Upvotes: 5

Related Questions