Martin
Martin

Reputation: 40573

Using method attributes to eliminate redundant code

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?

Upvotes: 1

Views: 368

Answers (2)

Eric Dahlvang
Eric Dahlvang

Reputation: 8292

Vote this up:

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

Upvotes: 1

Josh
Josh

Reputation: 44906

You should look at AOP techniques, specifically PostSharp

Upvotes: 4

Related Questions