Is it possible to build function at runtime in c#?
Say I have this method:
List<object> DoSomeWork(List<object> listOfItems, bool boolA, bool boolB)
{
var resultsList = new List<object>();
foreach (var value in listOfItems)
{
var resultOfWork = CallFunction(value);
if (boolA)
{
resultOfWork = AnotherFunctionCall(resultOfWork);
}
if (boolB)
{
resultOfWork = ThirdFunctionCall(resultOfWork);
}
resultsList.Add(resultOfWork);
}
return resultsList;
}
Is there a way I can dynamically build a function at runtime to prevent the need to check boolA and boolB for every iteration of the loop?
In my head I'd have something that looks like this:
List<object> DoSomeWork(List<object> listOfItems, bool boolA, bool boolB)
{
Func<object, object> processor = (toProcess) =>
{
var resultOfWork = CallFunction(toProcess);
}
if (boolA)
{
processor += { resultOfWork = AnotherFunctionCall(resultOfWork); };
}
if (boolB)
{
processor += { resultOfWork = ThirdFunctionCall(resultOfWork); };
}
processor += { return resultOfWork; };
var resultsList = new List<object>();
foreach (var value in listOfItems)
{
resultsList.Add(processor(value));
}
return resultsList;
}
Thanks in advance.