{"id":730,"date":"2024-12-07T10:14:51","date_gmt":"2024-12-07T16:14:51","guid":{"rendered":"https:\/\/kop.lat\/blog\/?p=730"},"modified":"2024-12-07T11:00:30","modified_gmt":"2024-12-07T17:00:30","slug":"events-in-c-net","status":"publish","type":"post","link":"https:\/\/kop.lat\/blog\/events-in-c-net\/","title":{"rendered":"Events in C# .Net"},"content":{"rendered":"\n<p>Events in C# are a powerful mechanism for implementing the <strong>observer pattern<\/strong>, enabling a class (publisher) to notify other classes (subscribers) about changes or actions. <\/p>\n\n\n\n<p>Events allows to build interactive and dynamic applications by providing a way to respond to user actions, data changes, or system states.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\"><strong>Core Concepts<\/strong><\/h3>\n\n\n\n<ol>\n<li><strong>Delegate<\/strong>:\n<ul>\n<li>Events are based on delegates.<\/li>\n\n\n\n<li>A delegate is a type-safe function pointer that defines the method signature for event handlers.<\/li>\n\n\n\n<li>The event can only invoke methods with the same signature as the associated delegate.<\/li>\n<\/ul>\n<\/li>\n\n\n\n<li><strong>Publisher<\/strong>:\n<ul>\n<li>A class that defines the event and is responsible for triggering it when an action occurs.<\/li>\n<\/ul>\n<\/li>\n\n\n\n<li><strong>Subscriber<\/strong>:\n<ul>\n<li>A class that listens to the event and defines the method(s) to handle it.<\/li>\n<\/ul>\n<\/li>\n\n\n\n<li><strong>Event<\/strong>:\n<ul>\n<li>It is a wrapper around a delegate that restricts the direct invocation of the delegate.<\/li>\n\n\n\n<li>Only the class that declares the event can raise it.<\/li>\n<\/ul>\n<\/li>\n<\/ol>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h3 class=\"wp-block-heading\"><strong>Defining and Using Events<\/strong><\/h3>\n\n\n\n<p>Here\u2019s a step-by-step breakdown:<\/p>\n\n\n\n<h4 class=\"wp-block-heading\"><strong>1. Define a Delegate<\/strong><\/h4>\n\n\n\n<div class=\"dm-code-snippet dark dm-slim-version default no-background-mobile\" snippet-height=\"\" style=\"background-color:#5E69FF\"><div class=\"control-language\"><div class=\"dm-buttons\"><div class=\"dm-buttons-left\"><div class=\"dm-button-snippet red-button\"><\/div><div class=\"dm-button-snippet orange-button\"><\/div><div class=\"dm-button-snippet green-button\"><\/div><\/div><div class=\"dm-buttons-right\"><a id=\"dm-copy-raw-code\"><span class=\"dm-copy-text\">Copy Code<\/span><span class=\"dm-copy-confirmed\" style=\"display:none\">Copied<\/span><span class=\"dm-error-message\" style=\"display:none\">Use a different Browser<\/span><\/a><\/div><\/div><pre class=\" line-numbers\"><code id=\"dm-code-raw\" class=\" no-wrap language-clike\">public delegate void Notify(); \/\/ Delegate definition<\/code><\/pre><\/div><\/div>\n\n\n\n<h4 class=\"wp-block-heading\"><strong>2. Declare an Event in the Publisher Class<\/strong><\/h4>\n\n\n\n<div class=\"dm-code-snippet dark dm-normal-version default no-background-mobile\" snippet-height=\"\" style=\"background-color:#20df90\"><div class=\"control-language\"><div class=\"dm-buttons\"><div class=\"dm-buttons-left\"><div class=\"dm-button-snippet red-button\"><\/div><div class=\"dm-button-snippet orange-button\"><\/div><div class=\"dm-button-snippet green-button\"><\/div><\/div><div class=\"dm-buttons-right\"><a id=\"dm-copy-raw-code\"><span class=\"dm-copy-text\">Copy Code<\/span><span class=\"dm-copy-confirmed\" style=\"display:none\">Copied<\/span><span class=\"dm-error-message\" style=\"display:none\">Use a different Browser<\/span><\/a><\/div><\/div><pre class=\" line-numbers\"><code id=\"dm-code-raw\" class=\" no-wrap language-clike\">public class Publisher\n{\n    public event Notify OnNotify; \/\/ Event based on the delegate\n\n    public void TriggerEvent()\n    {\n        if (OnNotify != null) \/\/ Check if there are any subscribers\n        {\n            OnNotify(); \/\/ Raise the event\n        }\n    }\n}<\/code><\/pre><\/div><\/div>\n\n\n\n<h4 class=\"wp-block-heading\"><strong>3. Subscribe to the Event<\/strong><\/h4>\n\n\n\n<div class=\"dm-code-snippet dark dm-normal-version default no-background-mobile\" snippet-height=\"\" style=\"background-color:#5E69FF\"><div class=\"control-language\"><div class=\"dm-buttons\"><div class=\"dm-buttons-left\"><div class=\"dm-button-snippet red-button\"><\/div><div class=\"dm-button-snippet orange-button\"><\/div><div class=\"dm-button-snippet green-button\"><\/div><\/div><div class=\"dm-buttons-right\"><a id=\"dm-copy-raw-code\"><span class=\"dm-copy-text\">Copy Code<\/span><span class=\"dm-copy-confirmed\" style=\"display:none\">Copied<\/span><span class=\"dm-error-message\" style=\"display:none\">Use a different Browser<\/span><\/a><\/div><\/div><pre class=\" line-numbers\"><code id=\"dm-code-raw\" class=\" no-wrap language-clike\">public class Subscriber\n{\n    public void HandleEvent()\n    {\n        Console.WriteLine(\"Event received and handled.\");\n    }\n}<\/code><\/pre><\/div><\/div>\n\n\n\n<h4 class=\"wp-block-heading\"><strong>4. Link Publisher and Subscriber<\/strong><\/h4>\n\n\n\n<div class=\"dm-code-snippet dark dm-slim-version default no-background-mobile\" snippet-height=\"\" style=\"background-color:#12d4ea\"><div class=\"control-language\"><div class=\"dm-buttons\"><div class=\"dm-buttons-left\"><div class=\"dm-button-snippet red-button\"><\/div><div class=\"dm-button-snippet orange-button\"><\/div><div class=\"dm-button-snippet green-button\"><\/div><\/div><div class=\"dm-buttons-right\"><a id=\"dm-copy-raw-code\"><span class=\"dm-copy-text\">Copy Code<\/span><span class=\"dm-copy-confirmed\" style=\"display:none\">Copied<\/span><span class=\"dm-error-message\" style=\"display:none\">Use a different Browser<\/span><\/a><\/div><\/div><pre class=\" line-numbers\"><code id=\"dm-code-raw\" class=\" no-wrap language-clike\">class Program\n{\n    static void Main()\n    {\n        Publisher publisher = new Publisher();\n        Subscriber subscriber = new Subscriber();\n\n        \/\/ Subscribe to the event\n        publisher.OnNotify += subscriber.HandleEvent;\n\n        \/\/ Trigger the event\n        publisher.TriggerEvent();\n    }\n}<\/code><\/pre><\/div><\/div>\n\n\n\n<p><strong>Output<\/strong>:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>Event received and handled.\n<\/code><\/pre>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h3 class=\"wp-block-heading\"><strong>Key Points About Events<\/strong><\/h3>\n\n\n\n<ol>\n<li><strong>Encapsulation<\/strong>:\n<ul>\n<li>Only the class that declares an event can trigger it. This ensures encapsulation.<\/li>\n\n\n\n<li>The <code>event<\/code> keyword restricts direct manipulation of the delegate by external classes.<\/li>\n<\/ul>\n<\/li>\n\n\n\n<li><strong>Multicast<\/strong>:\n<ul>\n<li>Events support multiple subscribers. All subscribed methods are invoked in the order of subscription.<\/li>\n<\/ul>\n<\/li>\n\n\n\n<li><strong>Thread Safety<\/strong>:\n<ul>\n<li>Use thread-safe techniques (e.g., <code>Interlocked.CompareExchange<\/code>) to manage event subscriptions in multi-threaded environments.<\/li>\n<\/ul>\n<\/li>\n<\/ol>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h3 class=\"wp-block-heading\"><strong>Common EventHandler Pattern<\/strong><\/h3>\n\n\n\n<p>C# provides the <code>EventHandler<\/code> and <code>EventHandler&lt;T&gt;<\/code> delegates for standardized event handling.<\/p>\n\n\n\n<h4 class=\"wp-block-heading\"><strong>Using EventHandler<\/strong><\/h4>\n\n\n\n<div class=\"dm-code-snippet dark dm-slim-version default no-background-mobile\" snippet-height=\"\" style=\"background-color:#ed17f4\"><div class=\"control-language\"><div class=\"dm-buttons\"><div class=\"dm-buttons-left\"><div class=\"dm-button-snippet red-button\"><\/div><div class=\"dm-button-snippet orange-button\"><\/div><div class=\"dm-button-snippet green-button\"><\/div><\/div><div class=\"dm-buttons-right\"><a id=\"dm-copy-raw-code\"><span class=\"dm-copy-text\">Copy Code<\/span><span class=\"dm-copy-confirmed\" style=\"display:none\">Copied<\/span><span class=\"dm-error-message\" style=\"display:none\">Use a different Browser<\/span><\/a><\/div><\/div><pre class=\" line-numbers\"><code id=\"dm-code-raw\" class=\" no-wrap language-clike\">public class Publisher\n{\n    public event EventHandler OnNotify;\n\n    public void TriggerEvent()\n    {\n        OnNotify?.Invoke(this, EventArgs.Empty);\n    }\n}\n\npublic class Subscriber\n{\n    public void HandleEvent(object sender, EventArgs e)\n    {\n        Console.WriteLine(\"Event received and handled.\");\n    }\n}<\/code><\/pre><\/div><\/div>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h3 class=\"wp-block-heading\"><strong>Advantages of Using Events<\/strong><\/h3>\n\n\n\n<ol>\n<li><strong>Decoupling<\/strong>:\n<ul>\n<li>Events decouple publishers and subscribers, making the system more modular and easier to maintain.<\/li>\n<\/ul>\n<\/li>\n\n\n\n<li><strong>Reusability<\/strong>:\n<ul>\n<li>Subscribers can reuse event handlers for different publishers.<\/li>\n<\/ul>\n<\/li>\n\n\n\n<li><strong>Flexibility<\/strong>:\n<ul>\n<li>Any number of subscribers can listen to the same event, providing great flexibility.<\/li>\n<\/ul>\n<\/li>\n<\/ol>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h3 class=\"wp-block-heading\"><strong>Real-World Examples<\/strong><\/h3>\n\n\n\n<ol>\n<li><strong>UI Controls<\/strong>: Button clicks (<code>Button.Click<\/code> event in Windows Forms\/WPF).<\/li>\n\n\n\n<li><strong>Data Changes<\/strong>: Notifications when data in a database changes.<\/li>\n\n\n\n<li><strong>Custom Notifications<\/strong>: Implementing event-driven architecture in business logic.<\/li>\n<\/ol>\n\n\n\n<p><\/p>\n","protected":false},"excerpt":{"rendered":"<p>Events in C# are a powerful mechanism for implementing the observer pattern, enabling a class (publisher) to notify other classes (subscribers) about changes or actions. Events allows to build interactive and dynamic applications by providing a way to respond to user actions, data changes, or system states. Core Concepts Defining and Using Events Here\u2019s a [&hellip;]<\/p>\n","protected":false},"author":1,"featured_media":232,"comment_status":"closed","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":[],"categories":[41,51,32,135],"tags":[53,23,136,54,137],"_links":{"self":[{"href":"https:\/\/kop.lat\/blog\/wp-json\/wp\/v2\/posts\/730"}],"collection":[{"href":"https:\/\/kop.lat\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/kop.lat\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/kop.lat\/blog\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/kop.lat\/blog\/wp-json\/wp\/v2\/comments?post=730"}],"version-history":[{"count":3,"href":"https:\/\/kop.lat\/blog\/wp-json\/wp\/v2\/posts\/730\/revisions"}],"predecessor-version":[{"id":739,"href":"https:\/\/kop.lat\/blog\/wp-json\/wp\/v2\/posts\/730\/revisions\/739"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/kop.lat\/blog\/wp-json\/wp\/v2\/media\/232"}],"wp:attachment":[{"href":"https:\/\/kop.lat\/blog\/wp-json\/wp\/v2\/media?parent=730"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/kop.lat\/blog\/wp-json\/wp\/v2\/categories?post=730"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/kop.lat\/blog\/wp-json\/wp\/v2\/tags?post=730"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}