Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Call a method each time before any other method is called

Tags:

c#

.net

I have a class where inside this class is one private method and many public methods. This private method must be called every time before any other method is called.

The simpliest approach would be calling the method in every method, but I don't like this approach. Is there any other way to achieve this ?

like image 569
user137348 Avatar asked Dec 28 '09 11:12

user137348


People also ask

What is a method call called?

The calling method is the method that contains the actual call. The called method is the method being called. They are different. They are also called the Caller and the Callee methods. For example int caller(){ int x=callee(); } int callee(){ return 5; }

Can a method call another method?

Similarly another method which is Method2() is being defined with 'public' access specifier and 'void' as return type and inside that Method2() the Method1() is called. Hence, this program shows that a method can be called within another method as both of them belong to the same class.

Can you call the same method within a method?

Yes you can. It is called recursion .

How do you call a method inside a method in Java?

Call a Method Inside main , call the myMethod() method: public class Main { static void myMethod() { System.out.println("I just got executed!"); } public static void main(String[] args) { myMethod(); } } // Outputs "I just got executed!"


2 Answers

You might be able to do something here with AOP, perhaps via PostSharp; but unles you are going to do this lots, I'd argue in favor of keeping it simple, and just add the extra code.

Of course, it gets more complex if you need polymorphism and need overrides to still call the method first (probably involving a public non-virtual method and a protected virtual method):

public void Foo() {
    Bar()
    FooCore();
}
protected virtual void FooCore() {...} // default Foo implementation
private void Bar() {...} // your special code
like image 101
Marc Gravell Avatar answered Sep 23 '22 21:09

Marc Gravell


This is a typical case of aspect oriented programming. As far as I know, there is no easy way to do this in .NET (except using byte-code enhancement or creation of a derived class at runtime, neither is easy. There are libraries doing it, for instance spring.net. I'm not sure if you really need this.)

I would try to avoid this situation at almost every cost - or call this method if there is really no other way.

like image 25
Stefan Steinegger Avatar answered Sep 20 '22 21:09

Stefan Steinegger