The C# event keyword is an access modifier for delegate members

Recently I had trouble getting COM events to work in a COM automation server written in C#. A visitor’s comment taught me that I was one keyword away from my goal. The event keyword.
The MSDN documentation on that is not clear at all. Browsing around on
the web I found a very beautiful story which was an eyeopener. Let me
me sum things up.

I had written a small COM add-in for Word which watched the
filesystem. Every time a new file was created the add-in directed Word
to open the file. The first simple version in VB.NET worked like a
snap. Creating a version which could watch multiple directories I ran
into trouble. To recapitulate  the source code (this one does work)

using System;
using System.IO;
using System.Collections;
using System.Runtime.InteropServices;

namespace WordUtils
{
    [Guid(FileWatcher.InterfaceId)]
    public interface IfileWatcher
    {
        int Watch(string dirName, string filter);
    }

    [Guid(FileWatcher.EventsId)]
    [InterfaceType(ComInterfaceType.InterfaceIsIDispatch)]
    public interface IfileWatcherEvents
    {
        void OnNewFile(string fullFileName);
    }

    [Guid(FileWatcher.ClassId)]
    [ClassInterface(ClassInterfaceType.None)]
    [ComSourceInterfaces(typeof(IfileWatcherEvents))]

    public class FileWatcher : IfileWatcher
    {
        internal const string ClassId = “44558DD7-87AD-433f-9B1B-C478233D6C69″;
        internal const string InterfaceId = “959A6835-4768-4cd5-89BE-7D408C2B86AA”;
        internal const string EventsId = “02E3954F-5DC1-4ad9-9167-354F0E82BCA3″;

        private ArrayList watchers = new ArrayList();

        private FileSystemWatcher watcher;

        public int Watch(string dirName, string filter)
        {
            watcher = new FileSystemWatcher(dirName, filter);
            watcher.EnableRaisingEvents = true;
            watcher.Created += new FileSystemEventHandler(watcher_Created);
            watchers.Add(watcher);
            return watchers.Count;
        }

        public event NewFile OnNewFile;

        private void watcher_Created(object sender, FileSystemEventArgs e)
        {
            if (e.Name.Substring(0,1) != “~”)
                OnNewFile(e.FullPath);
        }
    }

    [ComVisible(false)]
    public delegate void NewFile(string fileName);
}
 

The code defines a delegate type NewFile and has the OnNewFile property of this type. For a small background on COM events see this post. The eventhandler did show up in the Word VBA code but trying to instantiate the add-in 459-errors popped up. The essential difference in the code presented here is prefixing the delegate property with the event keyword.

To see what this keyword does took me some browsing on the web and a little experimentation. The ultimate source was a post on Julien Couvreur’s blog (Curiosity is a bliss, what a title !) C# events vs. delegates. A delegate property (like the OnNewFile member of my FileWatcher
class) is an eventhandler that will notify all delegate objects which
have subscribed. Delegates are pretty strange creatures, just look what
intellisense will show on one:

That’s quite a lot. You can do pretty heavy things here, like
getting to all code which has subscribed to receive notifications.
Looking at delegate property this way it doesn’t surprise me that
publishing it via COM  will lead to trouble.

That is where the event keyword comes to the rescue. It turns
the delegate field into a property and hides all members of the
delegate except addhandler (+=) and removehandler (-+). These are the
only two you need, one to subscribe and one to unsubscribe from
receiving notifications. Having applied the keyword my COM add-in
worked just fine.

I can really recommend reading the full story
yourself. Although there is one comment I would like to make. It states
that .NET restricts the signature of delegates on which the event keyword can be applied to that of a System.Eventhandler, that is

public delegate void EventHandler(
   object sender,
   EventArgs e
);

I have used several signatures (my NewFile delegate has one
string parameter) tried several scenarios and everything worked as
intended. Imho it would make no sense for a COM event to have this
signature. The sender and the eventargs are parameters which make a lot
of sense inside .NET but to a COM client written in (for instance)
Delphi they have no meaning at all.

In my original post I was a little disappointed in C# and had to
praise VB.NET for producing a working add-in. Later on I discoverd that
VB.NET did produce the same problem.
Now I have learned how to do it right in C#. But I cannot give you a
solution for VB.NET. There is so much more I have to learn. I’ll
continue to grow up in public.

This entry was posted in Coding. Bookmark the permalink. Follow any comments here with the RSS feed for this post.