I am getting lost in the many answers and examples here (Pass Method as Parameter using C#) about passing functions.
At the moment I have this:
private void AddWeekToHistory(ref XDocument xdoc, MSAHistoryWeek historyWeek)
{
// Do stuff
DetectStudentItemDescriptionAndType(studentItem,
bFirstStudent,
iClass,
out string strDesc,
out string strType);
// Do stuff
}
private void DetectStudentItemDescriptionAndType(MSAHistoryItemStudent studentItem, bool bFirstStudent, int iClass, out string strDesc, out string strType)
{
// Do stuff
}
I want to change AddWeekToHistory so that it can be passed a DetectStudentItemDescriptionAndType function. This is because I want to add a second version of that function that will use different logic (same parameters).
Ultimately I want to call AddWeekToHistory(ref xdoc, historyWeek, [name-of-func]);.
I understand from the answers that since I am using a void function that I should use Action. But I was getting lost in teh answers because the method in the original question there was passed a parameter and yet in the examples of running the passed function they did not actually pass parameters.
So rather than confuse an existing question I have asked a new one. What changes are needed for me to support passing DetectStudentItemDescriptionAndType and its variants (same attributes) as a function to AddWeekToHistory?
CodePudding user response:
You can't use any of the Action<...> delegates for a method with ref or out parameters. You will need a custom delegate instead:
public delegate void DetectStudentItemDescriptionAndTypeDelegate(MSAHistoryItemStudent studentItem, bool bFirstStudent, int iClass, out string strDesc, out string strType);
private void AddWeekToHistory(ref XDocument xdoc, MSAHistoryWeek historyWeek, DetectStudentItemDescriptionAndTypeDelegate detect)
{
// Do stuff
detect(studentItem,
bFirstStudent,
iClass,
out string strDesc,
out string strType);
// Do stuff
}
private void DetectStudentItemDescriptionAndType(MSAHistoryItemStudent studentItem, bool bFirstStudent, int iClass, out string strDesc, out string strType)
{
// Do stuff
}
AddWeekToHistory(xdoc, historyWeek, DetectStudentItemDescriptionAndType);
