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?