Why am I getting an error with conversion when I am trying to subscribe to event?

Viewed 50

I have a problem with the event understanding. For some reason, I can't subscribe to my event. The visual studio is saying

Error CS0029 Cannot implicitly convert type 'void' to 'FileSystemWatcher.FileSystemWatcher.Handler' FileSystemWatcher C:\Users\Diord\source\repos\FileSystemWatcher\FileSystemWatcher\Program.cs 16 Active

when I do this

fileSystemWatcher.Changed += ShowMessage();

class Program
{
    static void Main(string[] args)
    {
        FileSystemWatcher fileSystemWatcher = new FileSystemWatcher("C:\\");
        //next line is highlighted
        fileSystemWatcher.Changed += ShowMessage();
    }

    public void ShowMessage()
    {
        Console.WriteLine("Hello Event!");
    }
}
class FileSystemWatcher
{
    readonly string _path;

    private string[] Files { get; set; }

    public FileSystemWatcher(string path)
    {
        _path = path;
    }

    public delegate void Handler();

    public event Handler Changed;
}
2 Answers

You have to remove the brackets from ShowMessage(), as this is invoking the function and not "referencing" the method to the event.

The error message tells, that "void" (which is result of the function) can not be attached to the event.

In code:

fileSystemWatcher.Changed += ShowMessage;

The error is due to an incorrect assignment between a method signature (left part) and the result of the invocation (right part). Omitting the brackets indicates that you are interested in the signature, and not to effectively call the method.

This solves your issue:

fileSystemWatcher.Changed += ShowMessage;

However, in your example, you won't see anything, as your application will immediately exit as you have no message pump or simply you are not waiting on something.

Also, if the main thread is waiting for user input, you might not receive the event.

Consult the FileSysteWatcher documentation in order to learn how to use it. Particularly with threads (as you will need threads because you are in a console application).

Related