Compile Error C3918

·

·

1–2 minutes

In C#, we can check if an event variable is null before firing the event. For example:

public class MyClass
{
    public event EventHandler MyEvent;

    public void FireEvent()
    {
        // Check if there is any event handler registered.
        if (MyEvent != null)
        {
            MyEvent(this, new EventArgs());
        }
    }
}

But if we do the same thing in C++/CLI, we will get an compile error C3918.

ref class MyClass
{
public:
    event EventHandler^ MyEvent;

    void FireEvent()
    {
        if(MyEvent != nullptr) // C3918
        {
            MyEvent(this, gcnew EventArgs());
        }
    }
}

Here is the solution:

public ref class MyClass
{
    EventHandler^ m_myEvent;

public:
    event EventHandler^ MyEvent
    {
        void add(EventHandler^ handler)
        {
            m_myEvent += handler;
        }

        void remove(EventHandler^ handler)
        {
            m_myEvent -= handler;
        }

        void raise(Object^ sender, EventArgs^ e)
        {
            // Check if there is any event handler registered.
            if (m_myEvent != nullptr) 
            {
                m_myEvent->Invoke(sender, e);
            }
        }
    }
};

Related Articles

Get updates

Spam-free subscription, we guarantee. This is just a friendly ping when new content is out.

Go back

Your message has been sent

Warning
Warning
Warning.

2 responses to “Compile Error C3918”

  1. This doesnt work in VS 2010.. not sure about the other versions..

    “error C2146: syntax error : missing ‘;’ before identifier ‘MyEvent’”

    1. I’ve updated the code so that it compiles with VS2010. We need to specify the type of MyEvent and the parameters of the raise() method.

      Thanks,
      XueSong

Leave a comment