Search code examples
c#.nettimerevent-handlingeventhandler

Nonsense error message when manually calling EventHandler


If I have an EventHandler with the following signature:

public static void ProcessStuff(object sender, ElapsedEventArgs e)

And If I attempt to manually call the EventHandler like so:

ProcessStuff(this, System.Timers.ElapsedEventArgs.Empty);

Why Do I get the error message:

Argument 2: cannot convert from 'System.EventArgs' to 'System.Timers.ElapsedEventArgs'

EDIT: I also get the same error message If I set the manual call as:

ProcessStuff(this, System.EventArgs.Empty);

Solution

  • If we have a look at https://referencesource.microsoft.com/#System/services/timers/system/timers/ElapsedEventArgs.cs,fa59a445f56b7851

    we'll see that System.Timers.ElapsedEventArgs doesn't redeclare Empty:

    // No "Empty" (re-)declaration here
    public class ElapsedEventArgs : EventArgs {   
        private DateTime signalTime;
    
        internal ElapsedEventArgs(int low, int high) {        
            long fileTime = (long)((((ulong)high) << 32) | (((ulong)low) & 0xffffffff));
            this.signalTime = DateTime.FromFileTime(fileTime);                        
        }
    
        public DateTime SignalTime {
            get {
                return this.signalTime;
            }
        }
    }
    

    and that's why when we call System.Timers.ElapsedEventArgs.Empty we actually call System.EventArgs.Empty which is of type System.EventArgs:

    Console.Write(System.Timers.ElapsedEventArgs.Empty.GetType().Name);
    

    Finally, there's no implicit cast from System.EventArgs to System.Timers.ElapsedEventArgs