Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Run a method before all methods of a class

Tags:

Is it possible to do that in C# 3 or 4? Maybe with some reflection?

class Magic {      [RunBeforeAll]     public void BaseMethod()     {     }      //runs BaseMethod before being executed     public void Method1()     {     }      //runs BaseMethod before being executed     public void Method2()     {     } } 

EDIT

There is an alternate solution for this, make Magic a singleton and put your code on the getter of the static instance. That's what I did:

public class Magic {      private static Magic magic = new Magic();     public static Magic Instance     {         get         {             magic.BaseMethod();             return magic;         }     }      public void BaseMethod()     {     }      //runs BaseMethod before being executed     public void Method1()     {     }      //runs BaseMethod before being executed     public void Method2()     {     } } 
like image 932
WoF_Angel Avatar asked Feb 08 '12 11:02

WoF_Angel


People also ask

Which execute method before each test?

Methods annotated with the @Before annotation are run before each test. This is useful when we want to execute some common code before running a test. Notice that we also added another method annotated with @After in order to clear the list after the execution of each test.

Do methods go before or after main method?

Most (if not all) of the standard JDK libraries will follow it. This is IMHO a good reason to go with the methods-last approach. Regarding the placement of main among the methods, putting it first or last would work. If you find it "special" in some way, then put it dead last in the file.

Does the order of methods in Java matter?

Declaration order of methods never matters in C# or Java. Likewise it doesn't matter whether you declare a method before or after a variable that it uses.

Can you call method within method?

Java does not support “directly” nested methods. Many functional programming languages support method within method. But you can achieve nested method functionality in Java 7 or older version by define local classes, class within method so this does compile.


2 Answers

You can't do this automatically in C# - you should probably be looking at AOP, e.g. with PostSharp.

like image 162
Jon Skeet Avatar answered Oct 01 '22 12:10

Jon Skeet


There is an alternate solution for this, make Magic a singleton and put your code on the getter of the static instance. That's what i did.

public class Magic{  private static Magic magic; public static Magic Instance{   get     {    BaseMethod();     return magic;     } }  public void BaseMethod(){ }  //runs BaseMethod before being executed public void Method1(){ }  //runs BaseMethod before being executed public void Method2(){ } } 
like image 23
WoF_Angel Avatar answered Oct 01 '22 14:10

WoF_Angel