C# – Equivalent code in managed C++ & C# (Events in VB6)

ceventsmanaged

In VB6 events created in an ActiveX component were stated like this:

Public Event ProcessingComplete()

and called in that ActiveX component like:

RaiseEvent ProcessingComplete

I am creating a managed C++ DLL that I want to do the same thing with. It doesnt look like delegates are exactly what I want. I think the more appropriate item is an __event declaration. Help?!?

In the end, I have a C# application that I want to have a function like this:

MyObject::ProcessingComplete() <— This being the called function when "RaiseEvent" occurs.
{

}

Thanks.

Best Answer

It does sound like you want an event. In .NET, an event is just a delegate which by convention has a special signature. Here is a C# example of declaring an event in a class:

public class MyObject
{
    // ...

    public event EventHandler ProcessingComplete;

    // ...
}

EventHandler is a delegate with two parameters:

public delegate EventHandler(object sender, EventArgs e);

The sender is the object which raised the event and the EventArgs encode any information you want to pass to an event subscriber.

Every event is expected to follow this convention. If you wish to communicate specialized information for your event, you can create your own class derived from EventArgs. .NET defines a generically typed EventHandler delegate for this purpose, EventHandler<TEventArgs>. C# example:

class ProcessingCompleteEventArgs : EventArgs
{
    public ProcessingCompleteEventArgs(int itemsProcessed)
    {
        this.ItemsProcessed = itemsProcessed;
    }

    public int ItemsProcessed
    {
        get;
        private set;
    }
}

// ...

// event declaration would look like this:
public event EventHandler<ProcessingCompleteEventArgs> ProcessingComplete;

To subscribe to an event, use the += operator. To unsubscribe, use the -= operator.

void Start()
{
    this.o = new MyObject();
    this.o.ProcessingComplete += new EventHandler(this.OnProcessingComplete);

    // ...
}

void Stop()
{
    this.o.ProcessingComplete -= new EventHandler(this.OnProcessingComplete);
}

void OnProcessingComplete(object sender, EventArgs e)
{
    // ...
}

Inside your class, to fire the event, you can use the normal syntax to invoke a delegate:

void Process()
{
    // ...

    // processing is done, get ready to fire the event
    EventHandler processingComplete = this.ProcessingComplete;

    // an event with no subscribers is null, so always check!
    if (processingComplete != null)
    {
        processingComplete(this, EventArgs.Empty);
    }
}