Using [CallerMemberName] Attribute with Func delegate

419 Views Asked by At

I have common class which is used by both GUI and CommandLine applications

This class is passed a ReportError function reference which acts differently on GUI and CommandLine.

in the GUI:

 public int GUIReportError(String ToLog)
    {
        MessageBox.Show(ToLog);
        return 0;
    }

in the common Class members:

readonly Func<string, int> ReportError;

in the common Class Constructor:

public CommonClass(Func<string, int> ReportErrorFunc)
{
   ReportError=ReportErrorFunc;
}

Up to now, all is simple but I would integrate the [CallerMemberName] attribute to my log function

public int GUIReportError(String ToLog, [CallerMemberName] string CallingFunction="")
        {
            MessageBox.Show(ToLog, CallingFunction);
            return 0;
        }

So I also updated the Func definition:

 readonly Func<string,  string?, int> ReportError;

note udage of ? to tell it's optional parameter

But When I call this ReportError function, I get a compiler error as follows: CS7036: There is no argument given that corresponds to the required formal parameter 'arg2' of Func<string, string?,int>

if anyone already experienced this kind of problem, I would really appreciate.

1

There are 1 best solutions below

0
On

Yes, Solution is here.

The common Class declares a ReportError function which includes [CallerMemberName] as optional parameter.

This function then calls the delegate function passing 2 strings without having to deal with the optionnality.