melenaos / FileSystemSafeWatcher

Extends the FileSystemWatcher to trigger the events only when the file is ready for read
Apache License 2.0
34 stars 13 forks source link

Casting Error #2

Closed InteXX closed 6 years ago

InteXX commented 6 years ago

I'm getting an error on Line 287:

Unable to cast object of type 'FileSystemSafeWatcher' to type 'System.IO.FileSystemWatcher'.

Are you getting this as well?

melenaos commented 6 years ago

As you can see from the code FileSystemSafeWatcher doesn't inherit from FileSystemWatcher but it's using it.

internal class FileSystemSafeWatcher
 {
      private readonly FileSystemWatcher _fileSystemWatcher;
      .....
}

So you can't cast it to one another.

It has the same methods so you can replace it without any error but you cannot cast it.

InteXX commented 6 years ago

Right, I've got that. But the casting error comes when the Changed event is raised.

I'm about to try it with sending the internal FileSystemWatcher object to the event instead. That might work.

melenaos commented 6 years ago

Change the internal to public and change the OnChange event to accept FileSystemSafeWatcher.

Or

As you proposed change the if (Changed != null) Changed(this, e);

to

if (Changed != null) Changed(_fileSystemWatcher , e);

InteXX commented 6 years ago

OK, I figured it out.

I'd forgotten to update the event handler signature on my form.

FWIW... as a habit, one of the first things I do when handling an event is change the type of the Sender parameter to the type of the calling object. It saves on clunky code within the method when I need information from Sender.

melenaos commented 6 years ago

I am sorry but I haven't understand the tip here.

Can you give an example?

InteXX commented 6 years ago

Certainly.

When we double-click an event in a control's Property Grid, the designer adds this code to the class:

Private Sub cmdStart_Click(Sender As Object, e As EventArgs) Handles cmdStart.Click
End Sub

If we immediately change that to:

Private Sub cmdStart_Click(Sender As Button, e As EventArgs) Handles cmdStart.Click
End Sub

...we can access Sender's properties right away, without having to resort to clunky recasting code.

That's why I was getting the casting error—when I replaced FileSystemWatcher I didn't modify my event handler signature to accept a Sender of type FileSystemSafeWatcher, e.g.:

Private Sub _fswConfiguration_Changed(Sender As FileSystemSafeWatcher, e As FileSystemEventArgs) Handles fswConfiguration.Changed
End Sub

Once I straightened that little detail out, everything sailed right through.

melenaos commented 6 years ago

I see, Thanks for that

InteXX commented 6 years ago

YW