{"id":55,"date":"2023-05-17T06:43:32","date_gmt":"2023-05-17T05:43:32","guid":{"rendered":"https:\/\/ishooscode.com\/?p=55"},"modified":"2023-06-23T10:11:01","modified_gmt":"2023-06-23T09:11:01","slug":"delegates-in-application","status":"publish","type":"post","link":"https:\/\/ishooscode.com\/index.php\/2023\/05\/17\/delegates-in-application\/","title":{"rendered":"Benefits of delegates in application"},"content":{"rendered":"\n<p>Why should we use delegates. Delegate is one of the most wrongly interpreted word by developers in C#.\u00a0 Delegate is widely used inside .net framework itself. Let\u2019s go further and break that delegate wall that every interviewer asks. There are several benefits of delegates in application<\/p>\n\n\n\n<h2 class=\"wp-block-heading\"><strong>My Experience with <\/strong><strong>delegates in application<\/strong><\/h2>\n\n\n\n<p>In my all years of experience I have used delegate several times and noticed that after I am done with development who ever over takes that code from me is not able to grasp that particular delegate logic.<\/p>\n\n\n\n<p>If used wisely it can save a lot of time and lines of code but if used in inappropriately it will confuse everyone in future.<\/p>\n\n\n\n<p><strong>Purpose<\/strong><\/p>\n\n\n\n<p>It helps achieving following<\/p>\n\n\n\n<ol type=\"1\">\n<li>Encapsulation \/ Abstraction<\/li>\n\n\n\n<li>Security<\/li>\n\n\n\n<li>Callback<\/li>\n\n\n\n<li>Re-usability<\/li>\n<\/ol>\n\n\n\n<p>Most common definition of Delegate<\/p>\n\n\n\n<p>\u201cDelegate is a keyword in .net that is used as function pointer\u201d or<\/p>\n\n\n\n<p>\u201cDelegate is used for callbacks only\u201d<\/p>\n\n\n\n<p>Well nothing is wrong in these definition but these definition does not tell you the whole picture itself, it\u2019s more confusing<\/p>\n\n\n\n<p><strong>Characteristics<\/strong><\/p>\n\n\n\n<p>Delegate has few characteristic<\/p>\n\n\n\n<ol type=\"1\">\n<li>Type safe<\/li>\n\n\n\n<li>Takes method in assignment<\/li>\n<\/ol>\n\n\n\n<p>Let\u2019s start by an example \u2013<\/p>\n\n\n\n<p>First let\u2019s create our Product model. We are going to use this model<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>using System;\n\nnamespace Models\n{\n    public class Products\n    {\n        public string ProductName { get; set; }\n        public int ProductId { get; set; }\n\n    }\n}<\/code><\/pre>\n\n\n\n<p>Let\u2019s create and interface. General practice to create interface<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\nusing System.Threading.Tasks;\n\nnamespace BusinessLayer\n{\n    public interface ICustomer&lt;T&gt;\n    {\n        void Process(T products);\n    }\n}<\/code><\/pre>\n\n\n\n<p>Inherit this interface in class<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>using Models;\nusing System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\nusing System.Threading.Tasks;\n\nnamespace BusinessLayer\n{\n    public class FrequentCustomer : ICustomer&lt;Products&gt;\n    {\n        public void Process(Products product)\n        {\n            Console.WriteLine($\"Product Count : 1\");\n            Console.WriteLine(\"--Product Details--\");\n            Console.WriteLine($\"Name : {product.ProductName} Product Id : {product.ProductId}\");\n        }\n    }\n}\n<\/code><\/pre>\n\n\n\n<p>Process is the method which will be called by an anonymous later<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\nusing System.Threading.Tasks;\n\nnamespace ServiceCallManager\n{\n    public static class ServiceCaller\n    {\n        public static void Invoke&lt;TService&gt;(Action&lt;TService&gt; action)\n        {\n            Type typ = typeof(TService);\n            TService instance = (TService)Activator.CreateInstance(typ);\n            \n            action(instance);\n        }\n    }\n}\n<\/code><\/pre>\n\n\n\n<p>Invoke is the method which takes Action&lt;TService&gt; type argument, in .Net Action is delegate whose return type is void<\/p>\n\n\n\n<figure class=\"wp-block-image size-full is-resized\"><img decoding=\"async\" loading=\"lazy\" src=\"https:\/\/ishooscode.com\/wp-content\/uploads\/2023\/05\/Action-Delegate.png\" alt=\"delegates in application\" class=\"wp-image-56\" width=\"784\" height=\"333\" srcset=\"https:\/\/ishooscode.com\/wp-content\/uploads\/2023\/05\/Action-Delegate.png 782w, https:\/\/ishooscode.com\/wp-content\/uploads\/2023\/05\/Action-Delegate-300x127.png 300w, https:\/\/ishooscode.com\/wp-content\/uploads\/2023\/05\/Action-Delegate-768x326.png 768w\" sizes=\"(max-width: 784px) 100vw, 784px\" \/><\/figure>\n\n\n\n<p>See the summary, it says \u201c<em>encapsulates<\/em>\u201d<\/p>\n\n\n\n<p>Now we all know delegate takes method in assignment (Encapsulates method)<\/p>\n\n\n\n<p>Method can be in any form let\u2019s say anonymous methods,<\/p>\n\n\n\n<p>What is the anonymous method<\/p>\n\n\n\n<p>\u201cA method without name!\u201d<\/p>\n\n\n\n<p>Now let\u2019s look into our next class<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>using BusinessLayer;\nusing Models;\nusing ServiceCallManager;\nusing System;\nusing System.Collections.Generic;\nusing System.Dynamic;\nusing System.Linq;\nusing System.Net;\nusing System.Text;\nusing System.Threading;\nusing System.Threading.Tasks;\nnamespace CallbackExample\n{\n    class Program\n    {\n        static void Main(string&#91;] args)\n        {\n            IList&lt;Products&gt; products = new List&lt;Products&gt;();\n\n            Products product1 = new Products();\n            product1.ProductName = \"Rice\";\n            product1.ProductId = 1;\n            products.Add(product1);\n\n            product1 = new Products();\n            product1.ProductName = \"Dal\";\n            product1.ProductId = 2;\n            products.Add(product1);\n\n            product1 = new Products();\n            product1.ProductName = \"Chana\";\n            product1.ProductId = 3;\n            products.Add(product1);\n\n\n            ServiceCaller.Invoke&lt;FrequentCustomer&gt;(x =&gt; x.Process(product1));\n\n            Console.WriteLine();\n            Console.ReadKey();\n        }\n    }\n}\nServiceCaller.Invoke&lt;FrequentCustomer&gt;(x =&gt; x.Process(product1));\n<\/code><\/pre>\n\n\n\n<p>Remember that invoke method accepts delegate as argument and delegate encapsulates methods, so here inside Invoke method I am passing an anonymous method which will get invoked when action() is called which executes the anonymous method and calls the Process method of FrequentCustomer class<\/p>\n\n\n\n<p>Let\u2019s go step by step-<\/p>\n\n\n\n<ol type=\"1\">\n<li>Breakpoint comes to ServiceCaller.Invoke&lt;FrequentCustomer&gt;(x =&gt; x.Process(product1));<\/li>\n\n\n\n<li>It goes inside Invoke method of static ServiceCaller class<\/li>\n\n\n\n<li>Via reflection we are creating object of ServiceT type (You can ignore this if you don\u2019t understand reflection)<\/li>\n\n\n\n<li>At the last line of method action is called with parameter instance i.e. object of ServiceT type<\/li>\n\n\n\n<li>After action(instance) is called breakpoint comes to ServiceCaller.Invoke&lt;FrequentCustomer&gt;(x =&gt; x.Process(product1)); and it starts executing the x =&gt; x.Process(product1) part only<\/li>\n\n\n\n<li>You will notice that x is of type FrequentCustomer <\/li>\n\n\n\n<li><img decoding=\"async\" loading=\"lazy\" width=\"663\" height=\"62\" class=\"wp-image-57\" style=\"width: 800px;\" src=\"http:\/\/ishooscode.com\/wp-content\/uploads\/2023\/05\/Executing-Process.png\" alt=\"\" srcset=\"https:\/\/ishooscode.com\/wp-content\/uploads\/2023\/05\/Executing-Process.png 663w, https:\/\/ishooscode.com\/wp-content\/uploads\/2023\/05\/Executing-Process-300x28.png 300w\" sizes=\"(max-width: 663px) 100vw, 663px\" \/><\/li>\n\n\n\n<li>So this part of execution calls the Process method or FrequentCustomer and also passing local parameter in it<\/li>\n<\/ol>\n\n\n\n<p>Now the benefit of delegate here is I am able to local variable inside method i.e. product1 which may not be available in other class due to security reasons<\/p>\n\n\n\n<p>Delegate helps me implement <strong>Encapsulatiopn, Security, Callback<\/strong> (Obviously), <strong>Re-usability <\/strong>and if used wisely <strong>Polymorphism<\/strong> also<\/p>\n\n\n\n<p>For more blogs like this please visit http:\/\/codeinout.blogspot.com\/ of follow me on https:\/\/twitter.com\/ishooagarwal<\/p>\n\n\n\n<p>Thanks<\/p>\n","protected":false},"excerpt":{"rendered":"<p>Why should we use delegates. Delegate is one of the most wrongly interpreted word by&#8230;<\/p>\n","protected":false},"author":1,"featured_media":74,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"om_disable_all_campaigns":false,"_monsterinsights_skip_tracking":false,"_monsterinsights_sitenote_active":false,"_monsterinsights_sitenote_note":"","_monsterinsights_sitenote_category":0},"categories":[22],"tags":[20,18,15,16,19,17],"aioseo_notices":[],"_links":{"self":[{"href":"https:\/\/ishooscode.com\/index.php\/wp-json\/wp\/v2\/posts\/55"}],"collection":[{"href":"https:\/\/ishooscode.com\/index.php\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/ishooscode.com\/index.php\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/ishooscode.com\/index.php\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/ishooscode.com\/index.php\/wp-json\/wp\/v2\/comments?post=55"}],"version-history":[{"count":4,"href":"https:\/\/ishooscode.com\/index.php\/wp-json\/wp\/v2\/posts\/55\/revisions"}],"predecessor-version":[{"id":132,"href":"https:\/\/ishooscode.com\/index.php\/wp-json\/wp\/v2\/posts\/55\/revisions\/132"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/ishooscode.com\/index.php\/wp-json\/wp\/v2\/media\/74"}],"wp:attachment":[{"href":"https:\/\/ishooscode.com\/index.php\/wp-json\/wp\/v2\/media?parent=55"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/ishooscode.com\/index.php\/wp-json\/wp\/v2\/categories?post=55"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/ishooscode.com\/index.php\/wp-json\/wp\/v2\/tags?post=55"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}