views:

100

answers:

2

I have the following method which prints lines to the console.

public void MyMethod() {
    try {
        Console.WriteLine("Hello!");
        Console.WriteLine("My name is MyMethod");
    }
    finally {
        Console.WriteLine("Bye.");
    }
}

I have a few of these methods and they all do the same thing (i.e. try { "Hello"; Something; } finally { "Bye." }). To avoid redundancy and make my code clearer, I came up with the following:

public void SayHello(Action myName) {
    try {
        Console.WriteLine("Hello!");
        myName();
    }
    finally {
        Console.WriteLine("Bye.");
    }
}

public void MyMethod2() {
    SayHello(() => Console.WriteLine("My name is MyMethod"));
}

I like this technique, but I think it could be even better by using an attribute. Here is what I would like to ultimately achieve:

[SayHello]
public void MyMethod2() {
    Console.WriteLine("My name is MyMethod");
}

It would be great if I could simply add a method attribute to help me eliminate redundancy (i.e. try { "Hello"; Something; } finally { "Bye." }). Is it possible in C# to create such attribute?

+4  A: 

You should look at AOP techniques, specifically PostSharp

Josh
+1  A: 

Vote this up:

"CompileTimeAttribute to inject code at compile time" https://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=93682

Eric Dahlvang