Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing a method's name as a parameter

private void Method1()
{
    //Do something
    Log("Something","Method1");
}

private void Method2()
{
    //Do something
    Log("Something","Method2");
}

private void Log(string message, string method)
{
    //Write to a log file
    Trace.TraceInformation(message + "happened at " + method);
}

I have several methods like Method1 and Method2 above, and i would like some way pass the method's name as a parameter, without manually editing the code.

Is that possible?

like image 534
gorkem Avatar asked Jan 20 '14 09:01

gorkem


People also ask

How do you pass a method name as a parameter in Java?

Instead, we can call the method from the argument of another method. // pass method2 as argument to method1 public void method1(method2()); Here, the returned value from method2() is assigned as an argument to method1() . If we need to pass the actual method as an argument, we use the lambda expression.

Can we pass class name as parameter in Java?

Note that the parameter className must be fully qualified name of the desired class for which Class object is to be created. The methods in any class in java which returns the same class object are also known as factory methods. The class name for which Class object is to be created is determined at run-time.

Can you pass function name as parameter in Python?

Because functions are objects we can pass them as arguments to other functions. Functions that can accept other functions as arguments are also called higher-order functions. In the example below, a function greet is created which takes a function as an argument.

Can I pass a method as a parameter?

Information can be passed to methods as parameter. Parameters act as variables inside the method. Parameters are specified after the method name, inside the parentheses.


1 Answers

As of C# 5, this is really easy using caller info attributes:

private void Method1()
{
    //Do something
    Log("Something");
}

private void Method2()
{
    //Do something
    Log("Something");
}

private void Log(string message, [CallerMemberName] string method = null)
{
    //Write to a log file
    Trace.TraceInformation(message + "happened at " + method);
}

In terms of getting this working:

  • You must be using the C# 5 (or later) compiler, otherwise it won't know to handle the attributes specially
  • The attributes have to exist in your target environment. Options there:
    • In .NET 4.5 the attributes are simply present
    • For .NET 4 you can use the Microsoft.Bcl NuGet package
    • For earlier versions of .NET, copy the attribute declaration into your own code, making sure you use the same namespace. When you later move to a new version of .NET, you'll need to remove it again.
like image 97
Jon Skeet Avatar answered Sep 18 '22 12:09

Jon Skeet