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 ?
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; }
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.
Yes you can. It is called recursion .
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!"
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With