0

I'm getting the following error (A field initializer cannot reference the non-static field, method or property in EventHandler) on line:

FilesFound = FilesFound + 1;

Anyone know why and what would be the fix?

public class FileSearcher
{
    public event EventHandler<FileFoundArgs> FileFound;

    public int FilesFound { get; set; } = 0;
    
    EventHandler<FileFoundArgs> onFileFound = (sender, eventArgs) =>
    {
        Console.WriteLine(eventArgs.FoundFile);
        FilesFound = FilesFound + 1;
    };
    
    public FileSearcher()
    {
        FileFound += onFileFound;
    }

    public void Search(string directory, string searchPattern)
    {
        foreach (var file in Directory.EnumerateFiles(directory, searchPattern))
        {
            FileFound?.Invoke(this, new FileFoundArgs(file));
        }
    }
}

Thanks

William
  • 13
  • 1
  • Does this answer your question? [A field initializer cannot reference the nonstatic field, method, or property](https://stackoverflow.com/questions/14439231/a-field-initializer-cannot-reference-the-nonstatic-field-method-or-property) – Progman Oct 03 '20 at 15:58

1 Answers1

3

The error message says exactly what the problem is - your field initializer is using an instance member (FilesFound), via the lambda expression. You can't refer to other instance members within instance field initializers.

The simple fix is to move the initialization to the constructor:

private EventHandler<FileFoundArgs> onFileFound;

public FileSearcher()
{
    onFileFound = (sender, eventArgs) =>
    {
        Console.WriteLine(eventArgs.FoundFile);
        FilesFound = FilesFound + 1;     
    };
    FileFound += onFileFound;
}

Or if you're not going to use onFileFound anywhere else, get rid of it as a field entirely, and just subscribe directly to the event in the constructor:

private EventHandler<FileFoundArgs> onFileFound;

public FileSearcher()
{
    FileFound += (sender, eventArgs) =>
    {
        Console.WriteLine(eventArgs.FoundFile);
        FilesFound = FilesFound + 1;     
    };
}
Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
  • Thank you, I thought if I had set the default value as 0, it should be accessible, but seems that's not the case. – William Oct 03 '20 at 16:08