The Artima Developer Community
Sponsored Link

.NET Buzz Forum
The C# event keyword is an access modifier for delegate members

0 replies on 1 page.

Welcome Guest
  Sign In

Go back to the topic listing  Back to Topic List Click to reply to this topic  Reply to this Topic Click to search messages in this forum  Search Forum Click for a threaded view of the topic  Threaded View   
Previous Topic   Next Topic
Flat View: This topic has 0 replies on 1 page
Peter van Ooijen

Posts: 284
Nickname: petergekko
Registered: Sep, 2003

Peter van Ooijen is a .NET devloper/architect for Gekko Software
The C# event keyword is an access modifier for delegate members Posted: Aug 31, 2005 12:42 PM
Reply to this message Reply

This post originated from an RSS feed registered with .NET Buzz by Peter van Ooijen.
Original Post: The C# event keyword is an access modifier for delegate members
Feed Title: Peter's Gekko
Feed URL: /error.htm?aspxerrorpath=/blogs/peter.van.ooijen/rss.aspx
Feed Description: My weblog cotains tips tricks and opinions on ASP.NET, tablet PC's and tech in general.
Latest .NET Buzz Posts
Latest .NET Buzz Posts by Peter van Ooijen
Latest Posts From Peter's Gekko

Advertisement

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);
            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.

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

Topic: Extensible Design Previous Topic   Next Topic Topic: Architecture Testing Guide Released

Sponsored Links



Google
  Web Artima.com   

Copyright © 1996-2019 Artima, Inc. All Rights Reserved. - Privacy Policy - Terms of Use