Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing a random method as a parameter?

Tags:

c#

Is there any way in C# to pass a random method as a parameter?

To explain my question:

I want to write a simple Logger-Tool that reports the entering and leaving of a method with the passed arguments an the class and method name:

The log file I'm aiming at:

ENTERING: ClassOfDoom::MethodOfDoom( arg1={1} [int], arg2={true} [bool] )
LEAVING: ClassOfDoom::MethodOfDoom RETURNING 1 [int]

The code I have in mind:

class ClassOfDoom {
  // Remeber: MethodOfDoom is a _random_ method with _random_ arguments
  public int MethodOfDoom(int arg1, bool arg2) {
    Log.Entering(this, this.MethodOfDoom, arg1, arg2);
    ...
    return Log.Returing(this, this.MethodOfDoom, 1);
  }
}

Is there a way to achieve this? Or isn't C# as flexible as that?

Thanks in advance!

like image 317
Christian Smolka Avatar asked Feb 13 '26 16:02

Christian Smolka


1 Answers

You can make your logging function take a MethodBase argument and use MethodBase.GetCurrentMethod to pass the current method info as an argument.

Then, in the logger, you could check its properties Name and DeclaringType to get the method information. Also, passing parameters is easy by declaring a params object[] args parameter in the logging function:

public static void Entering(object obj, MethodBase methodInfo,
                            params object[] args) {
    Console.WriteLine("ENTERING {0}:{1}", methodInfo.DeclaringType.Name,
                                          methodInfo.Name);
    ...
}
like image 131
mmx Avatar answered Feb 15 '26 05:02

mmx



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!