I have a set of static functions like
internal static List<ClassA> GetListOfClassA (int id, string name) {...}
internal static string GetName (int id) {...}
internal static List<ClassB> GetCompleteListOfClassB() {...}
What I would like to accomplish here is the following (written as pseudocode)
List<ClassA> newList = new List<ClassA>;
string newname;
List<ClassB> newListB = new List<ClassB>;
Pipe (newList = GetListOfClassA (5, "myname"));
Pipe (newname = GetName (5));
Pipe (newListB = GetCompleteListOfClassB());
Pipe should be a function that accepts another function with parameters, executes some code and allows to return the value of the function to the caller. Pipe should do something like
{
Console.WriteLine ("Test");
if (CertainCondition==true)
return GetName (value);
else
wait(250);
}
I tried all kind of things like lambda expressions or actions but I can't get it to work generically so that all kinds of functions are accepted.
It would work when you did it like this:
List<ClassA> newList = new List<ClassA>();
string newname;
List<ClassB> newListB = new List<ClassB>();
newList = Pipe(() => GetListOfClassA(5, "myname"));
newname = Pipe(() => GetName(5));
newListB = Pipe(() => GetCompleteListOfClassB());
You can implement Pipe like this:
public static T Pipe<T>(Func<T> action)
{
Console.WriteLine("Entering pipe");
if (someCondition)
return action();
else
{
// do something else; but you still need to return something
return default(T);
}
}
You could also implement it as a function that does not return anything on its own but requires an Action that has a side effect (e.g. setting a variable):
Pipe(() => newList = GetListOfClassA(5, "myname"));
Pipe(() => newname = GetName(5));
Pipe(() => newListB = GetCompleteListOfClassB());
The implementation would be very similar except that you do not need to return anything:
public static T Pipe<T>(Func<T> action)
{
Console.WriteLine("Entering pipe");
if (someCondition)
action();
else
// do something else
}
The former has the benefit that there is a clear visibility of the side effect, i.e. the variable being set while the latter one leaves you in a situation where the variable could stay unassigned.
My first guess is that Pipe does not pass any arguments to the 'GetName' function.
In that case you can let Pipe accept an Action and use it like
Pipe(() => newList = GetListOfClassA(5, "myname"));
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