{"id":313,"date":"2020-10-15T11:16:14","date_gmt":"2020-10-15T05:46:14","guid":{"rendered":"http:\/\/sumitjangid.com\/?p=313"},"modified":"2021-09-18T12:06:02","modified_gmt":"2021-09-18T06:36:02","slug":"delegates","status":"publish","type":"post","link":"http:\/\/sumitjangid.com\/index.php\/2020\/10\/15\/delegates\/","title":{"rendered":"Delegates"},"content":{"rendered":"\n<p>It&#8217;s possible to write code for years without deliberately using&nbsp;<code>delegate<\/code>,&nbsp;<code>Action<\/code>, or&nbsp;<code>Func<\/code>&nbsp;types. I say &#8220;deliberately&#8221; because we may have used them without realizing it.<\/p>\n\n\n\n<p>Knowing what these types represent makes reading code easier. Knowing how to use them adds some useful tools to our developer toolbox.<\/p>\n\n\n\n<h2>What Is a `delegate`?<\/h2>\n\n\n\n<p>A&nbsp;<code>delegate<\/code>&nbsp;is a type that represents a method with a specific signature and return type.<\/p>\n\n\n\n<p>The declaration of a delegate looks exactly like the declaration of a method, except with the keyword&nbsp;<code>delegate<\/code>&nbsp;in front of it.<\/p>\n\n\n\n<p>Examples:<\/p>\n\n\n\n<ul><li>A delegate representing a method that adds two numbers and returns a result:<br><code>delegate int AddNumbers(int value1, int value2);<\/code><\/li><li>A delegate representing a method that logs an exception and doesn&#8217;t return anything:<br><code>delegate void LogException(Exception ex);<\/code><\/li><li>A delegate representing a function that converts some generic type to a&nbsp;<code>string<\/code>:<br><code>delegate string FormatAsString&lt;T&gt;(T input);<\/code><\/li><\/ul>\n\n\n\n<p>Just like classes and interfaces, we can declare delegates outside of classes or nested within classes. We can mark them&nbsp;<code>private<\/code>,&nbsp;<code>public<\/code>, or&nbsp;<code>internal<\/code>.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code> public delegate int MyDelegate(int x, int y);\n\n    class Program\n\n    {\n\n      static int Sum(int x, int y)\n\n        {\n\n            return x + y;\n\n        }\n\n        static void Main()\n\n        {\n\n            MyDelegate d = new MyDelegate(Sum);           \n\n            int result = d.Invoke(12, 15);\n \/\/ or your can use d(12,15);\n\n            Console.WriteLine(result);\n\n            Console.ReadLine();\n\n        }\n\n    }<\/code><\/pre>\n\n\n\n<h3>Multicast Delegate<\/h3>\n\n\n\n<p><\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>public class Program\n    {\n        public delegate void delmethod();\n        public static void method()\n        {\n            Console.WriteLine(\"Method 1\");\n        }\n        public static void method2()\n        {\n            Console.WriteLine(\"Method 2\");\n        }\n        public static void Main(string&#91;] args)\n        {\n            delmethod del = null;\n            del += method;\n            del += method2;\n            del.Invoke();\n        }\n    }<\/code><\/pre>\n\n\n\n<h3>Action, Func, and Predicate delegates in C#<\/h3>\n\n\n\n<p>Func is a delegate that points to a method that accepts one or more arguments and returns a value. <\/p>\n\n\n\n<p>Action is a delegate that points to a method which in turn accepts one or more arguments but returns no value. In other words, you should use Action when your delegate points to a method that returns void.<\/p>\n\n\n\n<p>A Predicate is a delegate that accepts one or more generic parameters and returns a Boolean value \u2014 you can assume it is something like Func&lt;T,bool&gt;. Predicate delegates are typically used to perform search operations on some data based on a set of criteria.<\/p>\n\n\n\n<h2><strong>Programming Action delegates in C#<\/strong><\/h2>\n\n\n\n<p>You can take advantage of delegates in C# to implement events and call back methods. A delegate in C# is similar to function pointers&nbsp;of&nbsp;C++, but C# delegates are type safe. You can pass methods as parameters to a delegate to allow the delegate to point to the method.<\/p>\n\n\n\n<p>The following code snippet illustrates the syntax for using Action delegate.<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\"><strong>Action<\/strong>&lt;<strong>TParameter<\/strong>&gt;<\/pre>\n\n\n\n<p>The following code listing shows how you can use Action delegate. This code snippet when executed would print the word \u201cHello!!!\u201d in the console window.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>static void Main(string&#91;] args)\n        {\n            Action&lt;string> action = new Action&lt;string>(Display);\n            action(\"Hello!!!\");\n            Console.Read();\n        }\nstatic void Display(string message)\n        {\n            Console.WriteLine(message);\n        }<\/code><\/pre>\n\n\n\n<h2><strong>Programming Func delegates in C#<\/strong><\/h2>\n\n\n\n<p>Let\u2019s now understand how we can work with Func delegates in C#. Here is the syntax for a Func delegate.<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\"><strong>Func<\/strong>&lt;<strong>TParameter<\/strong>, <strong>TOutput<\/strong>&gt;<\/pre>\n\n\n\n<p>The following code snippet illustrates how you can use a Func delegate in C#. It prints the value of Hra (calculated as 40% of basic salary). The basic salary is passed to it as an argument.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>static void Main(string&#91;] args)\n        {\n            Func&lt;int, double> func = new Func&lt;int, double>(CalculateHra);\n            Console.WriteLine(func(50000));\n            Console.Read();\n        }\n        static double CalculateHra(int basic)\n        {\n            return (double)(basic * .4);\n        }<\/code><\/pre>\n\n\n\n<h2><strong>Programming Predicate delegates in C#<\/strong><\/h2>\n\n\n\n<p>A Predicate delegate is typically used to search items in a collection or a set of data. Here is the syntax for a Predicate delegate. It Uses only one type argument.<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\"><strong>Predicate<\/strong>&lt;T&gt;<\/pre>\n\n\n\n<p>Note that Predicate&lt;T> is basically equivalent to Func&lt;T,bool>.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>static void Main(string&#91;] args)\r\n        {\r\n            Console.WriteLine(\"Hello World!\");\r\n            Predicate&lt;int> predicate = new Predicate&lt;int>(IsAbove5);\r\n            Console.WriteLine(predicate.Invoke(2));\r\n        }\r\n        static bool IsAbove5(int x)\r\n        {\r\n            return x>5;\r\n        }<\/code><\/pre>\n\n\n\n<h2>Using function as a parameter in a delegate<\/h2>\n\n\n\n<pre class=\"wp-block-code\"><code>        public delegate void delegatewithdelgateparameter(print str);\r\n        public delegate void printdelegate(string str);\r\n        static void Main(string&#91;] args)\r\n        {\r\n            Console.WriteLine(\"Hello World!\");\r\n            printdelegate del;\r\n            del = Print2;\r\n            del += Print3;\r\n            delegatewithdelgateparameter printm = Print1;\r\n            printm.Invoke(del);\r\n        }\r\n        static void Print1(print str)\r\n        {\r\n            str(\"Hello \");\r\n        }\r\n        static void Print2(string str)\r\n        {\r\n            Console.WriteLine(\"Hello2 \" +str);\r\n        }\r\n        static void Print3(string str)\r\n        {\r\n            Console.WriteLine(\"Hello3 \"+str);\r\n        }<\/code><\/pre>\n","protected":false},"excerpt":{"rendered":"<p>It&#8217;s possible to write code for years without deliberately using&nbsp;delegate,&nbsp;Action, or&nbsp;Func&nbsp;types. I say &#8220;deliberately&#8221; because we may have used them without realizing it. Knowing what these types represent makes reading code easier. Knowing how to&hellip; <\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":[],"categories":[3,4,2],"tags":[],"_links":{"self":[{"href":"http:\/\/sumitjangid.com\/index.php\/wp-json\/wp\/v2\/posts\/313"}],"collection":[{"href":"http:\/\/sumitjangid.com\/index.php\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"http:\/\/sumitjangid.com\/index.php\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"http:\/\/sumitjangid.com\/index.php\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"http:\/\/sumitjangid.com\/index.php\/wp-json\/wp\/v2\/comments?post=313"}],"version-history":[{"count":4,"href":"http:\/\/sumitjangid.com\/index.php\/wp-json\/wp\/v2\/posts\/313\/revisions"}],"predecessor-version":[{"id":351,"href":"http:\/\/sumitjangid.com\/index.php\/wp-json\/wp\/v2\/posts\/313\/revisions\/351"}],"wp:attachment":[{"href":"http:\/\/sumitjangid.com\/index.php\/wp-json\/wp\/v2\/media?parent=313"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"http:\/\/sumitjangid.com\/index.php\/wp-json\/wp\/v2\/categories?post=313"},{"taxonomy":"post_tag","embeddable":true,"href":"http:\/\/sumitjangid.com\/index.php\/wp-json\/wp\/v2\/tags?post=313"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}