Search code examples
c#staticraiseevent

Static event tries to declare non static instance


I am/was trying to create an event that my main form can subscribe to. This class will eventually be larger, it is for doing info/warning/error info to Windows event viewer (have not done that part yet) but it also sends to the form information. I have used events in many places, but this is the first time I am trying to make one in a static class. I didn't think there would be any issues, but I get this error "raiseEventtoForm: cannot declare instance members inside a static class."

All of my members are static- I am not sure why this is happening.

Am I not able to produce events in a static class? I can't find anything indicating I wouldn't be allowed to.

Edit: Updated delegate to not have static keyword.

public static class HABLAEvents
{
    public delegate void RaiseMessageEvent(string message, Color foreColor, Color backColor);
    public static event RaiseMessageEvent trigger = delegate { };
    public static void MessageEvent(string message, Color foreColor, Color backColor) { trigger(message, foreColor, backColor); }

    public static void raiseEventtoForm(string message, Color fc, Color bc)
    {
        MessageEvent(message, fc, bc);
    }
}

Edit: That same error "cannot declare instance members inside a static class" is also present for trigger and MessageEvent


Solution

  • here, take an example:

    using System;
    
    public static class Test
    {
        public static void Main()
        {
            EventsClass.someDelegateEvent += func;
            EventsClass.Raise();
    
        }
    
    
        public static void func(int number){
            Console.WriteLine(number);
        }
    
    }
    
    public static class EventsClass
    {
        public delegate void someDelegate(int num);
    
        public static event someDelegate someDelegateEvent;
    
        public static void Raise()
        {
            if (someDelegateEvent != null)
            someDelegateEvent(6);
        }
    }