#388 – Declaring and Using Private Events

You can declare private events in a class and they can be either instance or static events.  A private event is one that code within the class can subscribe to, but that is not visible to code outside the class.

For example, we can create a private static event in the Dog class that will fire whenever a new dog is created.

        private static event EventHandler<DogCreatedEventArgs> DogCreated;

This event will be visible only to code within the Dog class.

In the static constructor, we attach a handler that will record each Dog created.

        static Dog()
            Dog.DogCreated += new EventHandler<DogCreatedEventArgs>(Dog_DogCreated);

        static List<string> DogList = new List<string>();
        static void Dog_DogCreated(object sender, DogCreatedEventArgs e)

Finally, we fire the event from the instance constructor.

        public Dog(string name)
            Name = name;

            if (Dog.DogCreated != null)
                Dog.DogCreated(this, new DogCreatedEventArgs(name));

About Sean
Software developer in the Twin Cities area, passionate about .NET technologies. Equally passionate about my own personal projects related to family history and preservation of family stories and photos.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: