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?
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.
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.
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.
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.
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:
Microsoft.Bcl
NuGet package
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