I'm trying to make a method that accepts another method, and returns the value that the inner method returns, if that inner method isn't void. I'd like to do it without differentiating between Func<>
and Action<>
.
Essentially, I want the wrapped method to behave the exact same way as the unwrapped method, plus some functionality provided by the wrapper. The goal is simple enough, but it's hard to wrap my head around the implementation.
public int ReturnsInteger() {
Console.WriteLine("I return 42");
return 42;
}
public static T WrapperMethod(Func<T> someMethod) {
Console.WriteLine("Wrap start");
var result = someMethod();
Console.WriteLine("Wrap end");
return result;
}
private static void Main() {
var X = WrapperMethod(()=>ReturnsInt());
Console.WriteLine("X = " + X);
// Wrap start
// I return 42
// Wrap end
// X = 42
}
public void ReturnsNothing() {
Console.WriteLine("I return nothing");
return;
}
public static T WrapperMethod(Action someMethod) {
Console.WriteLine("Wrap start");
someMethod();
Console.WriteLine("Wrap end");
}
private static void Main() {
WrapperMethod(()=>ReturnsNothing());
// Wrap start
// I return nothing
// Wrap end
}