Call a method every time before calling any other method

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

The simplest approach is to call a method in all methods, but I do not like this approach. Is there any other way to achieve this?

+7
c #
source share
2 answers

You may be able to do something here with AOP, perhaps through PostSharp ; but unles, you are going to do this lots , I would argue in favor of its simplicity and just add additional code.

Of course, it becomes more complicated if you need polymorphism and the need for overriding in order to still call the first method (possibly involving an open 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 
+10
source share

This is a typical case of aspect-oriented programming . As far as I know, there is no easy way in .NET to do this (with the exception of using a byte code extension or creating a derived class at runtime, it's not that simple. There are libraries that do this, like spring.net . I'm not sure if You need it.)

I would try to avoid this situation at almost any cost β€” or call this method if no other way exists.

+5
source share

All Articles