none
Calling method in an Event Handler RRS feed

  • Question

  • Here is an event handler.

    private static void OnTimedEventDaily(object source, ElapsedEventArgs e)
    {
       DailyBackupProc(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day, DateTime.Now.Hour, DateTime.Now.Minute, DateTime.Now.Second, DateTime.Now.DayOfWeek);
    }
    

    However following error occurs

    An object reference is required for the non-static field, method, or property
    How could I use DateTime.Now in the event handler(static method)?

    Wednesday, December 13, 2017 7:10 PM

All replies

  • Hi,

    DateTime.Now is also static. Therefore wouldn't be DailyBackupProc a static method.

    regards, Hubert Hermanutz

    • Proposed as answer by Fei HuModerator Thursday, December 14, 2017 7:10 AM
    Wednesday, December 13, 2017 7:18 PM
  • So you mean to say just declare DailyBackupProc just as a static like following?

    static private void DailyBackupProc(int year, int month, int day, int hour, int minute, int second, DayOfWeek week)
          

    Wednesday, December 13, 2017 7:22 PM
  • Hi,

    if DailyBackupProc is static, this will work for your example.

    Better way will be, to use instance members. Means caller and nested function aren't static:

    private void OnTimedEventDaily(object source, ElapsedEventArgs e) {

    this.DailyBackupProc(...)

    }

    private void DailyBackupProc(int year, int month, int day, int hour, int minute, int second, DayOfWeek week) {

    }

    regards, Hubert Hermanutz

    • Proposed as answer by Fei HuModerator Thursday, December 14, 2017 7:10 AM
    Wednesday, December 13, 2017 8:08 PM
  • Hello Jeff0803,

    Please, you could mark the helpful reply as answer if the issue has been solved. And if you have any concerns, please do not hesitate to let us know.

    Best regards,

    Neil Hu


    MSDN Community Support
    Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact MSDNFSF@microsoft.com.

    Sunday, December 24, 2017 8:34 AM
    Moderator