• Skip to main content
  • Skip to primary sidebar
  • Skip to secondary sidebar
  • Skip to footer

Computer Notes

Library
    • Computer Fundamental
    • Computer Memory
    • DBMS Tutorial
    • Operating System
    • Computer Networking
    • C Programming
    • C++ Programming
    • Java Programming
    • C# Programming
    • SQL Tutorial
    • Management Tutorial
    • Computer Graphics
    • Compiler Design
    • Style Sheet
    • JavaScript Tutorial
    • Html Tutorial
    • Wordpress Tutorial
    • Python Tutorial
    • PHP Tutorial
    • JSP Tutorial
    • AngularJS Tutorial
    • Data Structures
    • E Commerce Tutorial
    • Visual Basic
    • Structs2 Tutorial
    • Digital Electronics
    • Internet Terms
    • Servlet Tutorial
    • Software Engineering
    • Interviews Questions
    • Basic Terms
    • Troubleshooting
Menu

Header Right

Home » C# » Advanced » Events in C#
Next →
← Prev

Events in C#

By Dinesh Thakur

In object-oriented languages, objects expose encapsulated functions called methods. Methods are encapsulated functions which run when they are invoked.

Sometimes, however, we think of the process of method invocation more grandly. In such a case, the method invocation is termed an ‘event’, and the running of the method is the ‘handling’ of the event. An standard example of an event is a user’s selection of a button on a graphical user interface; this action may trigger a number of methods to ‘handle’ it

Events provide a way for a class or object to notify other classes or objects when something of interest happens. The class that sends (or raises) the event is called the publisher and the classes that receive (or handle) the event are called subscribers.

Even modeling is fully based the delegate model of C# language. According to the event modeling, publishers send out their event only to subscribers who have subscribed to receive the specific event.

                          publishers send out their event only to subscribers who have subscribed to receive the specific event.

Let us look at how events are declare in C# syntax:

 

[modifier] event [type] [Event identifier];

In the above syntax, the modifier is any allowed scope modifier. The type must be delegate and the Event identifier is any valid identifier which you will refer in you program.

What distinguishes events from other method invocations is not, however, that they must   generated externally. Any internal change in the state of a program can be used as an event. Rather, what distinguishes events is that they are backed by a particular ‘subscription notification’ model. An arbitrary class must be able to ‘subscribe to’ (or declare its interest in) a particular event, and then receive a ‘notification’ (ie. have one of its methods run) whenever the event occurs.

Events have the following properties:

• The publisher determines when an event is raised, the subscribers determine what action is taken is response to the event.

• An event can have multiple subscribers. A subscriber can handle multiple events from multiple publishers.

• Events that the have no subscriber are never called.

• Events are commonly used to signal user actions such as button clicks or menu selection in graphical user interface.

• When an event has multiple subscribers, the event handlers are invoked synchronously when an event is raised.

• Events can be used to synchronize threads.

• In the .NET framework class library, events are based on the Event Handler delegate and the EventArgs base class.

Delegates (in particular multicast delegates) are essential in realizing this subscription notification model.

Here is the simple user defined event shown in sample example.

 

Simple userdefined Event.

 

using system;

public delegate void Edelegate();

public class sample

{

public event Edelegate eve; II Event declaration

public void first ()

{ Console.writeLine (“I am First”); }

public void second ()

{ console.writeLine (“I am second”); }

public void Third ()

{Console.writeLine (“I am Third”); }

public void eveCall ()

{ if (eve!=null) eve (); }

}

class Demo

{ pubic static void Main ()

{

sample s = new sample ();

S.eve + = new Edelegate (s.first);

S.evecall ();

console.writeLine (U “);

S.eve + = new Edelegate (S.second);

S.evecal1 ();

console.writeLine(U— ..-.-.–“);

S.eve + = new Edelegate (s.Third);

S.evecal1 ();

}

}

 

OUTPUT:

 

I am First         I am First

I am First         I am Second

I am Second    I am Third

 

Predefined Event of Timer.

 

using system;

using system.collections;

using system.Text;

using System.Timers;

 

class EventTest

{

 

static int counter = 0;

static string str = “This string will appear one letter at

a time.”;

 

static void Main(string[] args)

{

Timer myTimer = new Timer(lOO);

myTimer.Elapsed +=new ElapsedEventHandler(writeChar);

myTimer.Start();

console.ReadLine();

}

 

static void writechar(object source, ElapsedEventArgs e)

{

console.write (str[counter++ % str.Length]);

}

}

OUTPUT: (program wills tenninate by pressing any key)

This string will appear one letter at a time. This string will appear one letter at a time.

This string wills appea.

Tips for Events

The code above demonstrates some points about event-handling which are not enforced by the language architecture, bl,lt are used throughout the .Net framework as good practice.

1. When you want to raise an event in code, you don’t tend to trigger the class’s event object directly. Rather, you call a ‘protected, virtual’ method to trigger it (cf. the onMyEvent method above).

2. By convention, when events are raised they pass two objects to their subscribers. The first is a reference to the class raising the event; the second is an instance of the System.EventArgs class which contains any arbitrary data about the event

3. If an event is not interested in passing data to subscribers, then its defining delegate will still reference an EventArgs object (but a null value will be passed by the event).

If an event should pass data to its subscribers, however, then it is standard to use a specific class which derives from the EventArgs class to hold this data.

 

4. When you write a class which inherits from an event-raising base class, you can ‘intercept’ an event by overriding the method used to raise it. The following code illustrates such an intercept – classes which subscribe to the event will never receive notifications about it.

 

protected override void onMyEvent(EventArgs args)

{

console.writeLine(“hello”);

}

 

If you want subscribers to continue to receive notifications despite such an ‘intercepting’ method, however, then you can call the base class method as in the following:

 

protected override void onMyEvent(EventArgs args)

{

console.writeLine(“hello”);

base.onMyEvent(args);

}

You’ll also like:

  1. Keyboard Events in Java Example
  2. JTree Events Example in Java
  3. Keyboard Events in Java Applet
  4. What is Visual Basic Event? Give Some Examples of Events
  5. What is the Servlet container raises the life cycle events in servlet program?
Next →
← Prev
Like/Subscribe us for latest updates     

About Dinesh Thakur
Dinesh ThakurDinesh Thakur holds an B.C.A, MCDBA, MCSD certifications. Dinesh authors the hugely popular Computer Notes blog. Where he writes how-to guides around Computer fundamental , computer software, Computer programming, and web apps.

Dinesh Thakur is a Freelance Writer who helps different clients from all over the globe. Dinesh has written over 500+ blogs, 30+ eBooks, and 10000+ Posts for all types of clients.


For any type of query or something that you think is missing, please feel free to Contact us.


Primary Sidebar

C# Tutorials

C# Tutorials

  • C# - .NET Languages Types
  • C# - Dot Net
  • C# - Dot Net Framework
  • C# - Inheritance Types
  • C# - Features
  • C# - CTS
  • C# - CLS
  • C# - CLR
  • C# - Console
  • C# - MSIL
  • C# - Base Class Library
  • C# - Web Forms Creation
  • C# - C# Vs C++
  • C# - Statements Types
  • C# - JIT
  • C# - CLI
  • C# - Controls Types
  • C# - String Types
  • C# - Execution Model

Other Links

  • C# - PDF Version

Footer

Basic Course

  • Computer Fundamental
  • Computer Networking
  • Operating System
  • Database System
  • Computer Graphics
  • Management System
  • Software Engineering
  • Digital Electronics
  • Electronic Commerce
  • Compiler Design
  • Troubleshooting

Programming

  • Java Programming
  • Structured Query (SQL)
  • C Programming
  • C++ Programming
  • Visual Basic
  • Data Structures
  • Struts 2
  • Java Servlet
  • C# Programming
  • Basic Terms
  • Interviews

World Wide Web

  • Internet
  • Java Script
  • HTML Language
  • Cascading Style Sheet
  • Java Server Pages
  • Wordpress
  • PHP
  • Python Tutorial
  • AngularJS
  • Troubleshooting

 About Us |  Contact Us |  FAQ

Dinesh Thakur is a Technology Columinist and founder of Computer Notes.

Copyright © 2025. All Rights Reserved.

APPLY FOR ONLINE JOB IN BIGGEST CRYPTO COMPANIES
APPLY NOW