{"id":727,"date":"2024-12-07T10:09:45","date_gmt":"2024-12-07T16:09:45","guid":{"rendered":"https:\/\/kop.lat\/blog\/?p=727"},"modified":"2024-12-07T11:00:58","modified_gmt":"2024-12-07T17:00:58","slug":"delegates-in-c-net","status":"publish","type":"post","link":"https:\/\/kop.lat\/blog\/delegates-in-c-net\/","title":{"rendered":"Delegates in C# .Net"},"content":{"rendered":"\n<p>Delegates in C# are <strong>type-safe function pointers<\/strong> that allow methods to be passed as parameters, stored as variables, or dynamically invoked at runtime. <\/p>\n\n\n\n<p>They are a cornerstone of event-driven programming and play a key role in defining <strong>events<\/strong>, <strong>callbacks<\/strong>, and <strong>lambda expressions<\/strong>.<\/p>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h3 class=\"wp-block-heading\"><strong>Key Features of Delegates<\/strong><\/h3>\n\n\n\n<ol>\n<li><strong>Type Safety<\/strong>: Delegates enforce that the signature of the target method matches the delegate definition.<\/li>\n\n\n\n<li><strong>Multicast Capability<\/strong>: A delegate can reference multiple methods and invoke them in sequence.<\/li>\n\n\n\n<li><strong>Encapsulation<\/strong>: Delegates encapsulate methods, making them easier to work with dynamically.<\/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 Delegates<\/strong><\/h3>\n\n\n\n<h4 class=\"wp-block-heading\"><strong>1. Declare a Delegate<\/strong><\/h4>\n\n\n\n<p>A delegate is defined using the <code>delegate<\/code> keyword.<\/p>\n\n\n\n<div class=\"dm-code-snippet dark dm-normal-version default no-background-mobile\" snippet-height=\"\" style=\"background-color:#008b95\"><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=\" no-line-numbers\"><code id=\"dm-code-raw\" class=\" no-wrap language-clike\">public delegate void MyDelegate(string message);<\/code><\/pre><\/div><\/div>\n\n\n\n<p>This declaration specifies that <code>MyDelegate<\/code> can point to any method with:<\/p>\n\n\n\n<ul>\n<li>A <code>void<\/code> return type<\/li>\n\n\n\n<li>A single <code>string<\/code> parameter<\/li>\n<\/ul>\n\n\n\n<h4 class=\"wp-block-heading\"><strong>2. Assign Methods to a Delegate<\/strong><\/h4>\n\n\n\n<div class=\"dm-code-snippet dark dm-normal-version default no-background-mobile\" snippet-height=\"\" style=\"background-color:#69bac3\"><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=\" no-line-numbers\"><code id=\"dm-code-raw\" class=\" no-wrap language-clike\">public class Program\n{\n    public static void ShowMessage(string message)\n    {\n        Console.WriteLine(message);\n    }\n\n    public static void Main()\n    {\n        MyDelegate del = ShowMessage; \/\/ Assigning a method to the delegate\n        del(\"Hello, Delegates!\");    \/\/ Invoking the delegate\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>Hello, Delegates!\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>Multicast Delegates<\/strong><\/h3>\n\n\n\n<p>Delegates can point to multiple methods. This is called a multicast delegate.<\/p>\n\n\n\n<h4 class=\"wp-block-heading\"><strong>Example:<\/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=\" no-line-numbers\"><code id=\"dm-code-raw\" class=\" no-wrap language-clike\">public class Program\n{\n    public static void ShowMessage(string message)\n    {\n        Console.WriteLine($\"Message: {message}\");\n    }\n\n    public static void ShowUppercaseMessage(string message)\n    {\n        Console.WriteLine($\"Uppercase Message: {message.ToUpper()}\");\n    }\n\n    public static void Main()\n    {\n        MyDelegate del = ShowMessage;\n        del += ShowUppercaseMessage; \/\/ Add another method\n\n        del(\"Hello, Multicast Delegates!\"); \/\/ Both methods are invoked\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>Message: Hello, Multicast Delegates!\nUppercase Message: HELLO, MULTICAST DELEGATES!\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>Using Delegates as Parameters<\/strong><\/h3>\n\n\n\n<p>Delegates are commonly used to pass methods as parameters, enabling dynamic behavior.<\/p>\n\n\n\n<h4 class=\"wp-block-heading\"><strong>Example:<\/strong><\/h4>\n\n\n\n<div class=\"dm-code-snippet dark dm-normal-version default no-background-mobile\" snippet-height=\"\" style=\"background-color:#7FC8A9\"><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=\" no-line-numbers\"><code id=\"dm-code-raw\" class=\" no-wrap language-clike\">public class Program\n{\n    public delegate int MathOperation(int x, int y);\n\n    public static int Add(int x, int y)\n    {\n        return x + y;\n    }\n\n    public static int Multiply(int x, int y)\n    {\n        return x * y;\n    }\n\n    public static void PerformOperation(int a, int b, MathOperation operation)\n    {\n        Console.WriteLine($\"Result: {operation(a, b)}\");\n    }\n\n    public static void Main()\n    {\n        PerformOperation(5, 3, Add);       \/\/ Pass Add method\n        PerformOperation(5, 3, Multiply);  \/\/ Pass Multiply method\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>Result: 8\nResult: 15\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>Anonymous Methods with Delegates<\/strong><\/h3>\n\n\n\n<p>You can define inline methods using <strong>anonymous methods<\/strong>.<\/p>\n\n\n\n<h4 class=\"wp-block-heading\"><strong>Example:<\/strong><\/h4>\n\n\n\n<div class=\"dm-code-snippet dark dm-slim-version default no-background-mobile\" snippet-height=\"\" style=\"background-color:#2b91eb\"><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-php\">MyDelegate del = delegate (string message)\n{\n    Console.WriteLine($\"Anonymous: {message}\");\n};\n\ndel(\"Hello from Anonymous Method!\");<\/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>Lambda Expressions with Delegates<\/strong><\/h3>\n\n\n\n<p>Lambda expressions provide a concise way to define methods for delegates.<\/p>\n\n\n\n<h4 class=\"wp-block-heading\"><strong>Example:<\/strong><\/h4>\n\n\n\n<div class=\"dm-code-snippet dark dm-slim-version default no-background-mobile\" snippet-height=\"\" style=\"background-color:#38ebff\"><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-php\">MyDelegate del = (message) => Console.WriteLine($\"Lambda: {message}\");\n\ndel(\"Hello from Lambda!\");<\/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>Built-In Delegates<\/strong><\/h3>\n\n\n\n<p>C# provides several built-in generic delegates:<\/p>\n\n\n\n<ol>\n<li><strong>Action<\/strong>: Represents a method that takes input parameters but does not return a value. <\/li>\n<\/ol>\n\n\n\n<div class=\"dm-code-snippet dark dm-normal-version default no-background-mobile\" snippet-height=\"\" style=\"background-color:#f700ff\"><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\">Action&lt;string> action = (message) => Console.WriteLine(message); \naction(\"Hello, Action!\");<\/code><\/pre><\/div><\/div>\n\n\n\n<ol>\n<li><strong>Func<\/strong>: Represents a method that takes input parameters and returns a value. <\/li>\n<\/ol>\n\n\n\n<div class=\"dm-code-snippet dark dm-normal-version default no-background-mobile\" snippet-height=\"\" style=\"background-color:#7FC8A9\"><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-php\">Func&lt;int, int, int> func = (x, y) => x + y; \nConsole.WriteLine(func(5, 3)); \n\/\/ Output: 8<\/code><\/pre><\/div><\/div>\n\n\n\n<ol>\n<li><strong>Predicate<\/strong>: Represents a method that takes an input parameter and returns a <code>bool<\/code>. <\/li>\n<\/ol>\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\">Predicate&lt;int> isPositive = (x) => x > 0;\nConsole.WriteLine(isPositive(5));\n\/\/ Output: True<\/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 Delegates<\/strong><\/h3>\n\n\n\n<ol>\n<li><strong>Encapsulation<\/strong>: Encapsulate method references into a single entity.<\/li>\n\n\n\n<li><strong>Flexibility<\/strong>: Enable dynamic method invocation.<\/li>\n\n\n\n<li><strong>Reusability<\/strong>: Simplify code by reusing delegates across different parts of an application.<\/li>\n\n\n\n<li><strong>Event Handling<\/strong>: Form the foundation of event handling in .NET.<\/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>When to Use Delegates<\/strong><\/h3>\n\n\n\n<ul>\n<li><strong>Event Handling<\/strong>: Link UI or system events to custom logic.<\/li>\n\n\n\n<li><strong>Callback Methods<\/strong>: Notify one component when another component completes an operation.<\/li>\n\n\n\n<li><strong>Dynamic Invocation<\/strong>: Allow users to supply custom behavior at runtime.<\/li>\n<\/ul>\n\n\n\n<p><\/p>\n","protected":false},"excerpt":{"rendered":"<p>Delegates in C# are type-safe function pointers that allow methods to be passed as parameters, stored as variables, or dynamically invoked at runtime. They are a cornerstone of event-driven programming and play a key role in defining events, callbacks, and lambda expressions. Key Features of Delegates Defining and Using Delegates 1. Declare a Delegate A [&hellip;]<\/p>\n","protected":false},"author":1,"featured_media":278,"comment_status":"closed","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":[],"categories":[41,1,51,32,135],"tags":[23,136,54],"_links":{"self":[{"href":"https:\/\/kop.lat\/blog\/wp-json\/wp\/v2\/posts\/727"}],"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=727"}],"version-history":[{"count":6,"href":"https:\/\/kop.lat\/blog\/wp-json\/wp\/v2\/posts\/727\/revisions"}],"predecessor-version":[{"id":740,"href":"https:\/\/kop.lat\/blog\/wp-json\/wp\/v2\/posts\/727\/revisions\/740"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/kop.lat\/blog\/wp-json\/wp\/v2\/media\/278"}],"wp:attachment":[{"href":"https:\/\/kop.lat\/blog\/wp-json\/wp\/v2\/media?parent=727"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/kop.lat\/blog\/wp-json\/wp\/v2\/categories?post=727"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/kop.lat\/blog\/wp-json\/wp\/v2\/tags?post=727"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}