Search code examples
c#windowsserviceevent-log

System.Diagnostics.EventLog Cannot be Accessed with an Instance Reference


I'm creating a Windows Service and have a slight issue when trying to write to the EventLog. I have the following code;

class WindowsService : ServiceBase
{
    public WindowsService()
    {
        ((ISupportInitialize)this.EventLog).BeginInit();

        if (!EventLog.SourceExists(this.ServiceName))
        {
            EventLog.CreateEventSource(this.ServiceName, "Application");
        }
        ((ISupportInitialize)this.EventLog).EndInit();
    }
}

This is based on the MSDN article and another SO question on here, and it worked up until last night however this morning it doesn't work with the error

Member 'EventLog.SourceExists(string)' cannot be accessed with an instance reference; qualify it with a type name instead

Member 'EventLog.CreateEventSource(string, string)' cannot be accessed with an instance reference; qualify it with a type name instead

I'm not sure why, I've checked against a backup and that too is throwing an error.

Does anyone have any ideas?

Thank you


Solution

  • SourceExists and CreateEventSource are static methods, you need to qualify them with the type name rather than an instance variable. Based on the error and on this:

    this.EventLog
    

    presumably you have an instance variable called EventLog. Rename it to something less confusing, such as CurrentEventLog. Any meaningful name that doesn't conflict with an existing name.

    Basically, don't name your variables the same as their types. That's just inviting confusion not only from the compiler but also from anybody who has to maintain that code.