C# Tutorial

C# Tutorial C# First Application C# Variables C# Data Types C# Operators C# Keywords

C# Control Statement

C# If Statements C# Switch Statements C# for Loop C# While Loop C# do While loop C# Jump Statements C# Function C# functions with out variable

C# Arrays

C# Arrays

C# Function

C# Function call by value C# Call by reference C# Passing array to function C# Multidimensional Arrays C# Jagged Arrays C# Params C# Array Class C# Command Line Arguments

C# Object Class

C# Object and Classes C# Constructors C# Destructor C# this Keyword C# static field C# static class C# Static Constructor C# Structs C# enum C# Properties

C# Inheritance

C# Inheritance C# Multilevel Inheritance C# Aggregation C# Member overloading C# Method Overriding C# Base

C# Polymorphism

C# Polymorphism C# Sealed

C# Abstraction

C# Abstraction C# Interface

C# Namespace

C# Namespace C# Access Modifiers C# Encapsulation

C# Strings

C# String

C# Misc

C# Design Patterns Dictionary in C# Boxing and Unboxing in C# Ref and Out in C# Serialization in C# Dispose and Finalize in C# CONSOLE LOG IN C# Get File extension in C# Insert query in c# Difference Between List and Dictionary in C# Getters and Setters in C# Extension Methods in C# Insert query in c# CONSOLE LOG IN C# Get File extension in C# Random.NextDouble() Method in C# Binary Search in C# Difference between Delegates and Interfaces in C# Double.IsFinite() Method in C# Index Constructor in C# Abstraction in C# Basic OOPS Concepts In C# Queue.CopyTo() Method in C# single.compareto() method in C# C# Throw Exception in Constructor DECODE IN C# file.setlastwritetimeutc() method in C# Convert Object to List in C# convert.ToSByte(string, IFormatProvider) Method in C# C# Declare Delegate in Interface console.TreatControl C As Input property in C# Copying the queue elements to 1-D Array in C# Array.Constrainedcopy() Method in C# C# in and out Char.IsLetterOrDigit() method in C# Debugging in C# decimal.compare() method in C# Difference between Console.Read and Console.Readline in C# Metadata in C# C# Event Handler Example Default Interface Methods in C# Difference between hashtable and dictionary in C# C# program to implement IDisposable Interface Encapsulation in C# SortedList.IndexOfVaalue(Object) Method in C# Hash Maps in C# How to clear text files in C# How to Convert xls to xlsx in C# Foreach loop in C# FIFO in C# How to handle null exception in C# Type.Is Instance Of Type() Method in C# How to add data into MySQL database using C# How to use angular js in ASP net Csharp decimal.compare() method in Csharp Difference between Console.Read and Console.Readline in Csharp How to Implement Interface in Csharp char.IsUpper() Method in C# Index Of Any() Method in C# Quantifiers in C# C# program to Get Extension of a Given File C# Error Logging C# ENCRIPTION Can we create an object for Abstract Class in C# Console.CursorVisible in C# SortedDictionary Implementation in C# C# Hash Table with Examples Setting the Location of the Label in c# Collections in c# Virtual Keyword in C# Reverse of string in C# String and StringBuilder in C# Encapsulation in C# SortedList.IndexOfVaalue(Object) Method in C# Hash Maps in C# How to clear text files in C# How to Convert xls to xlsx in C# Foreach loop in C# FIFO in C# How to handle null exception in C# Type.Is Instance Of Type() Method in C# How to add data into MySQL database using C# How to use angular js in ASP net Csharp decimal.compare() method in Csharp Difference between Console.Read and Console.Readline in Csharp How to Implement Interface in Csharp char.IsUpper() Method in C# Index Of Any() Method in C# Quantifiers in C# C# program to Get Extension of a Given File Difference between ref and out in C# Singleton Class in C# Const And Readonly In Csharp BinaryReader and BinaryWriter in C# C# Attributes C# Delegates DirectoryInfo Class in C# Export and Import Excel Data in C# File Class in C# FileInfo Class in C# How to Cancel Parallel Operations in C#? Maximum Degree of Parallelism in C# Parallel Foreach Loop in C# Parallel Invoke in C# StreamReader and StreamWriter in C# TextReader and TextWriter in C# AsQueryable() in C# Basic Database Operations Using C# C# Anonymous Methods C# Events C# Generics C# Indexers C# Multidimensional Indexers C# Multithreading C# New Features C# Overloading of Indexers Difference between delegates and events in C# Operator overloading in C# Filter table in C# C# Queue with Examples C# Sortedlist With Examples C# Stack with Examples C# Unsafe Code File Handling in C# HashSet in C# with Examples List Implementation in C# SortedSet in C# with Examples C# in Depth Delegates and Events in C# Finally Block in C# How to Split String in C# Loggers in C# Nullable Types in C# REVERSE A STRING IN C# TYPE CASTING IN C# What is Generics in C# ABSTRACT CLASS IN C# Application of pointer in C# Await in c# READONLY AND CONSTANT IN C# Type safe in C# Types of Variables in c# Use of delegates in c# ABSTRACT CLASS IN C# Application of pointer in C# Await in c# READONLY AND CONSTANT IN C# Type safe in C# Types of Variables in c# Use of delegates in c# ABSTRACT CLASS IN C# Application of pointer in C# Await in c# READONLY AND CONSTANT IN C# Type safe in C# Types of Variables in c# Use of delegates in c# Atomic Methods Thread Safety and Race Conditions in C# Parallel LINQ in C# Design Principles in C# Difference Between Struct And Class In C# Difference between Abstraction and Encapsulation in C# Escape Sequence Characters in C# What is IOC in C# Multiple Catch blocks in C# Appdomain in C# Call back methods in C# Change Datetime format in C# Declare String array in C# Default Access Specifier in c# Foreach in LINQ C# How to compare two lists in C# How to Convert String to Datetime in c# How to get only Date from DateTime in C# Ispostback in asp net C# JSON OBJECT IN C# JSON STRINGIFY IN C# LAMBDA FUNCTION IN C# LINQ Lambda Expression in C# Microservices in C# MSIL IN C# Reference parameter in C# Shadowing(Method hiding) in C# Solid principles in C# Static Members in C# Task run in C# Transaction scope in C# Type Conversion in c# Unit of Work in C# Unit Test Cases in c# User Defined Exception in c# Using Keyword in C# Var Keyword in C# What is gac in C#

C# Events

At this Event, Microsoft hopes to inform developers about the features of both new and old products. Microsoft will notify the developer of the Event, in this case, via Email or other advertising channels. Therefore, Microsoft will act as a publisher in this instance, raising the Event and informing the developers of it. Developers will handle the Event as a subscriber to the Event.

Similar principles apply to Events in C#. Various procedures, such as click and mouseover, can be carried out by a button. The Event that we will use to inform the other subscriber classes about upcoming events is contained in the custom class. As a result, we will define the Event in this instance and alert the other classes that it includes the event handler.

The Event is an encapsulated delegate. Events with delegates are supported by both C# and.NET.  Delegates must be used to managing events since there is a close relationship between events and delegates in terms of dispatching them. While the class sending the Event is known as the publisher, the class handling the Event is referred to as a subscriber.

Key Points about the Events are:

The essential components of the significant events are as follows:

  • In C#, the event handler takes two parameters and outputs void.
  •  The first argument of the Event is also known as the source that will publish the item.
  •  Several subscribers may be present for a single event.
  •  Typically, the Event is used for a single user action, such hitting a button.
  •  If the Event has many subscribers, the event handler is called synchronously.

Declaration of the Event

Steps for Implementing the Event

To define the Event in the class, the delegate's event type must first be specified.

Invokation of the Event

if (CellEvent != null) CellEvent(this, e);

Only within the class where the Event was declared are we able to call the Event.

Hooking up the Event

OurEventClass.OurEvent += new ChangedEventHandler(OurEventChanged);

Detach the Event

OurEventClass.OurEvent -= new ChangedEventHandler(OurEventChanged);

Delegates function as a function's pointer. It is a reference data type and contains the method's reference. System. The Delegate class was implicitly descended from the delegate class.

A delegate may be declared using the delegate keyword and the signature.

Syntax of Delegates:

<access modifier> delegate <return type><delegate_name>(<parameters>) 

Example of Delegates:

public delegate void PrintWord(int value);

Any method that shares the same return type and specified parameters as PrintWord can be pointed at using the previously mentioned PrintWord delegate. Here, we'll look at a declaration and use of the PrintWord delegates.

The PrintWord delegates in the previously mentioned example accept an int-type parameter and return void. We assign the PrintNum name method and declare the PrintWord type method in the primary () method. The PrintWord delegate will now be called, which will then call the PrintNum function. If the PrintWord delegates variable is assigned to the PrintMoney method, the PrintMoney method will be invoked in the same manner.

As illustrated below, we can build the delegate object using the new operator and specifying the method's name.

PrintWord printDel = new PrintWord(PrintNum); 

Delegates can be declared as shown below:

public delegate void someevent(); 

public organize Event

Event - Basic Conceptual Implementation:

CODE:

The code is as follows:

class Program

{

    static void Main(string[] args)

    {

        Publisher publisher = new Publisher();

        Subscriber subscriber = new Subscriber(publisher);

        publisher.Add(new Product

        {

            ProductName = "Complan", Price = 20

        });

        publisher.Add(new Product

        {

            ProductName = "Horlics", Price = 120

        });

        publisher.Add(new Product

        {

            ProductName = "Boost", Price = 200

        });

        subscriber.UnSubscribeEvent();

        Console.ReadKey();

    }

}

OUTPUT:

The Output for the following program will be:

A New Product Added.

A New Product Added.

A New Product Added.

Passing data by extending EventArgs:

To transfer data in the second parameter of the event handler from the publisher to subscribers, you must define a class that derives from the EventArgs class and stores the data you need to pass in the class.

The program that follows demonstrates how to send information (Email and Phone) from the publisher (Order class) to the subscribers (Email and SMS classes).

How it works.

The OrderEventArgs class, which derives from the EventArgs class, should first be defined.

Next, define the Event using the OrderEventArgs type of EventHanlder:

public event EventHandler<OrderEventArgs> OnCreated;

Third, create a new instance of the OrderEventArgs class and raise an event:

OnCreated(this, new OrderEventArgs { Email = email, Phone = phone });

The OrderEventArgs object in this statement holds the Email and phone information.

Fourth, modify the signature of the Send() method to take advantage of the OrderEventArgs:

public static void Send(object sender, OrderEventArgs e)

The OrderEventArgs object in the Send() method provides access to the Email and phone number.

Events are used as a channel of communication between objects in object-oriented programming. They enable one object—the publisher—to alert other objects—the subscribers—when a particular action or state change occurs. The selected event handler code can then be executed by the subscribers to respond to the Event.

Declaration and Subscription:

Based on events in C# is delegates. A delegate type represents a pointer to a method with a specific signature. It would help if you created an event delegate that contains the signature of the methods that can handle the Event before you can declare an event. Subscribers must define the method signature specified by the delegate, and it serves as a contract for them.

Once defined, the event delegate can declare an event inside a class. The event keyword is customarily prefixed before the Event, which can be public or private. By attaching their event handler methods to the Event, subscribers can then subscribe to the Event.

Raising and Handling Events:

The publisher invokes the Event as if it were a delegate to raise it. This is commonly accomplished by including an event-triggering protected or protected virtual method in the publisher class. This method calls the event delegate and passes any necessary event arguments.

Subscribers take care of the Event by implementing event handler methods that adhere to the event delegate's signature. When the Event is raised, these methods are carried out. The same Event can have several subscribers attach it with their event handlers so that everyone can react when it happens.

Null Checking and Event Invocation:

To ensure it has subscribers, it is crucial to carry out a null check before triggering an event. This is commonly done by ensuring that the Event is not null before executing it using the null-conditional operator (?.).

Event Arguments:

Through event arguments, events can also provide subscribers with additional data. Event arguments are derived or custom classes derived from the introductory class EventArgs. These classes have fields or properties that can store the relevant event-related data.

The kind of event arguments an event delegate will utilize can be specified when it is declared. You can make a new instance of the event arguments class and provide it to the event invocation when raising the Event. To retrieve pertinent information about the Event, subscribers can then access the event arguments within their event handler methods.

Unsubscribing from Events:

Events allow subscribers to stop receiving notifications by unsubscribing. This is commonly accomplished by separating the event handler procedure from the Event using the -= operator. When events are no longer required, it's crucial to unsubscribe from them to prevent memory leaks and pointless event alerts.

Event Access Modifiers:

Depending on the intended level of encapsulation, events can have a variety of access modifiers, including internal, protected, private, and public. The access modifier depends on which classes can subscribe to and raise the Event.

Event Best Practices:

It's crucial to follow some of the few best practices while working with events to ensure clean and maintainable code:

  • Use the event keyword to declare events whenever possible, as it offers more protection and encapsulation.
  • Give your events and event handler functions meaningful names to make your code easier to read.
  • Record the occurrences and how they are used to instruct subscribers on handling them.
  • To prevent unauthorized event invocation outside the class, avoid making events publicly settable.

Example:

CODE:

The code is as follows:

public class Publisher

{

    public event EventHandler MyEvent;

    protected virtual void OnMyEvent(EventArgs e)

    {

        MyEvent?.Invoke(this, e);

    }

    public void DoSomething()

    {

        OnMyEvent(EventArgs.Empty);

    }

}

public class Subscriber

{

    public void HandleEvent(object sender, EventArgs e)

    {

        Console.WriteLine("Event handled by Subscriber");

    }

}

public class Program

{

    public static void Main()

    {

        Publisher publisher = new Publisher();

        Subscriber subscriber = new Subscriber();

        publisher.MyEvent += subscriber.HandleEvent;

        publisher.DoSomething();  // Output: Event handled by Subscriber

    }

}

OUTPUT:

The Output for the following program will be:

Event handled by Subscriber

In the above example, the Publisher class declares an event of type EventHandler with the name MyEvent. The event handler method HandleEvent is implemented by the Subscriber class. The event handler method is subscribed to the Event using the += operator, generating an instance of Publisher and Subscriber. The Event is raised, and the handler is carried out when DoSomething is invoked.

Conclusion:

In C#, events offer an effective publish-subscribe method for objects to communicate with one another. They provide loose coupling between components, enabling them to communicate while unaware of one another. Publishers can alert subscribers to specific actions or state changes by declaring and raising events, and subscribers can reply by implementing event handler methods.

Delegates, which specify the signature of the event handler methods, are the foundation of events. An event delegate specifies the method signature subscribers must follow when an event is declared. The += operator is then used by subscribers to connect their event handler functions to the Event.

C# events give objects a powerful mechanism to interact and respond to actions or state changes. They encourage modularity and extensibility in applications and enable loose connectivity between components. Your C# programs' functionality and flexibility can be improved by comprehending events and how to use them.

The publisher invokes the event delegate to raise an event, which causes it to occur and notifies all event handlers who subscribe to it. Before triggering the Event, running a null check is crucial to ensure subscribers are associated. Event arguments can be used to pass subscribers more information, providing essential details about the Event.

Subscribers manage events by providing event handler methods that match the delegate's signature. The event handler methods are executed when the Event is raised, enabling subscribers to react using their unique logic. When using events, it's best to follow some rules, such as giving them meaningful names, documenting how to use them, and guaranteeing thread safety when working with multi-threaded systems.

Unsubscribing from events is crucial to avoid memory leaks and pointless event alerts. You can improve the flexibility, extensibility, and maintainability of your C# programs by comprehending and successfully using events. Events offer a flexible and decoupled method to handle object communication, improving the organization and maintainability of your code.