{"id":164,"date":"2018-02-19T19:46:00","date_gmt":"2018-02-19T18:46:00","guid":{"rendered":"https:\/\/kindsonthegenius.com\/blog\/2018\/02\/19\/what-are-delegates-in-c\/"},"modified":"2020-08-22T09:15:40","modified_gmt":"2020-08-22T07:15:40","slug":"what-are-delegates-in-c","status":"publish","type":"post","link":"https:\/\/kindsonthegenius.com\/blog\/what-are-delegates-in-c\/","title":{"rendered":"What are Delegates in C#"},"content":{"rendered":"<div style=\"color: #555555; font-size: 18px; line-height: 30px; text-align: justify;\">\n<div style=\"font-family: 'segoe ui';\">A delegate in C# can be conpared to a function pointer in C and C++. It allows programmers to specify what the funtion to be called will look like without having to specify the particular function.<\/p>\n<div style=\"clear: both; text-align: center;\"><a href=\"https:\/\/3.bp.blogspot.com\/-8AXTYAEghrs\/WospmIT3dCI\/AAAAAAAAA8w\/px1ZpURRkWs9SkVDfYnQO0UF6LujTH2vACLcBGAs\/s1600\/Delegates%2Bin%2BC%2523.jpg\" style=\"margin-left: 1em; margin-right: 1em;\"><img decoding=\"async\" loading=\"lazy\" border=\"0\" data-original-height=\"777\" data-original-width=\"1455\" height=\"170\" src=\"https:\/\/3.bp.blogspot.com\/-8AXTYAEghrs\/WospmIT3dCI\/AAAAAAAAA8w\/px1ZpURRkWs9SkVDfYnQO0UF6LujTH2vACLcBGAs\/s320\/Delegates%2Bin%2BC%2523.jpg\" width=\"320\" \/><\/a><\/div>\n<p>A delegate is a reference type variable that hods th reference to a function, which can change at runtime.<br \/>Delegates are very useful when programing UI controles where events have to be implemented for callbacks.<\/p>\n<p><b>Normal Function Call Without Delegate<\/b><br \/>In normal function call, we specify the function to be called directly. So if a funciton is defined an a class named SomeClass and has a function called Do(), then the function can be called using the syntax:<br \/>SomeFunction.Do()<\/p>\n<hr \/>\n<pre style=\"background-color: white; margin: 0em; overflow: auto;\"><code style=\"color: black; font-family: &quot;consolas&quot; , &quot;courier new&quot; , &quot;courier&quot; , monospace; font-size: 10pt;\"><span style=\"color: blue;\">namespace<\/span> DelegateDemo<br \/>{<br \/>    <span style=\"color: blue;\">public<\/span> <span style=\"color: blue;\">class<\/span> SomeClass<br \/>    {<br \/>        <span style=\"color: blue;\">public<\/span> <span style=\"color: blue;\">void<\/span> Process()<br \/>        {<br \/>            Console.WriteLine(<span style=\"color: #a31515;\">\"Process() begin\"<\/span>);<br \/>            Console.WriteLine(<span style=\"color: #a31515;\">\"Process() end\"<\/span>);<br \/>        }<br \/>    }<br \/><br \/>    <span style=\"color: blue;\">public<\/span> <span style=\"color: blue;\">class<\/span> Test<br \/>    {<br \/>        <span style=\"color: blue;\">static<\/span> <span style=\"color: blue;\">void<\/span> Main(<span style=\"color: blue;\">string<\/span>[] args)<br \/>        {<br \/>            SomeClass myClass = <span style=\"color: blue;\">new<\/span> SomeClass();<br \/>            myClass.Process();<br \/>        }<br \/>    }<br \/>}<\/code><\/pre>\n<hr \/>\n<p>The above code works perfectly in most situaition. However, there may be sometimes when we dont&#8217; want to call&nbsp; a function directly. We need to pass it to some ohter method to call it. This would be neccessary&nbsp; in an event driven system sucha s a graphical user interface applicaiton. In this case we would like some code to be executed when a user clicks on a button, or when I want to log some informaiton but cannot at the moment specify how it would be logged.<\/p>\n<p><b>Three Steps to Using a Delegate<\/b><br \/>Step 1: Declaration<br \/>Step 2: Instantiation<br \/>Step 3: Invocation <\/p>\n<p><b>Declaring Delegates in C#<\/b><br \/>Declaration of delegates determines that methods that can be referenced by the delegate. For a delegate to refer to a function, the function must have the signature of that delegate.<\/p>\n<p><i>Consider the example:<\/i><br \/>public delegate int SomeDelegate (string );<\/p>\n<p>The delegate declare above can be used to reference any function that has a single string parameter and returns an int type variable.<br \/>The syntax for delegate declaration is :<\/p>\n<p>delegate return-type identifier ([parameters]);<\/p>\n<p>where:<br \/><b>return-type: <\/b>The return type&nbsp; which has to be the same as the return type of the function<br \/><b>identifier: <\/b>Name of the delegate<br \/><b>parameters<\/b>: The parameters to the function<\/p>\n<p><b>Instatiating Delegates<\/b><br \/>After a delegate have been declared, a delegate object msut be created with the new keyword and be associated with the a particular method. When creating a delegate, the argument passed to the new expression is written similar to a function call, but without arguments to the function.<br \/>For example:<\/p>\n<p>public delegate void writeString(string s);<\/p>\n<p>writeString d1 = new writeString(ToScreen);<br \/>writeString d2 = new writeString(ToFile);<\/p>\n<p>In the above example, a delegate called writeString() is delared that takes a single string.<br \/>The we instantiate two delegates d1 and d2 using&nbsp; <\/p>\n<p>The function below illustrates how to delare, instantiate and use delegates to reference functions that take int values and returns int values.<\/p>\n<hr \/>\n<pre style=\"background-color: white; margin: 0em; overflow: auto;\"><code style=\"color: black; font-family: &quot;consolas&quot; , &quot;courier new&quot; , &quot;courier&quot; , monospace; font-size: 10pt;\">    <span style=\"color: blue;\">class<\/span> Program<br \/>    {<br \/>        <span style=\"color: blue;\">static<\/span> <span style=\"color: blue;\">int<\/span> num = 10;<br \/>        <span style=\"color: blue;\">delegate<\/span> <span style=\"color: blue;\">int<\/span> NumDelegate(<span style=\"color: blue;\">int<\/span> n); <\/code><code style=\"color: black; font-family: &quot;consolas&quot; , &quot;courier new&quot; , &quot;courier&quot; , monospace; font-size: 10pt;\"><code style=\"color: black; font-family: &quot;consolas&quot; , &quot;courier new&quot; , &quot;courier&quot; , monospace; font-size: 10pt;\"><span style=\"color: green;\">\/\/DECLARE A DELEGATE NumDelegage<\/span><\/code><br \/>        <span style=\"color: blue;\">public<\/span> <span style=\"color: blue;\">static<\/span> <span style=\"color: blue;\">int<\/span> Add(<span style=\"color: blue;\">int<\/span> val1)<br \/>        {<br \/>            num = num + val1;<br \/>            <span style=\"color: blue;\">return<\/span> num;<br \/>        }<br \/>        <span style=\"color: blue;\">public<\/span> <span style=\"color: blue;\">static<\/span> <span style=\"color: blue;\">int<\/span> Mult(<span style=\"color: blue;\">int<\/span> val2)<br \/>        {<br \/>            num = num + val2;<br \/>            <span style=\"color: blue;\">return<\/span> num;<br \/>        }<br \/>        <span style=\"color: blue;\">public<\/span> <span style=\"color: blue;\">static<\/span> <span style=\"color: blue;\">int<\/span> getNum()<br \/>        {<br \/>            <span style=\"color: blue;\">return<\/span> num;<br \/>        }<br \/>        <span style=\"color: blue;\">static<\/span> <span style=\"color: blue;\">void<\/span> Main(<span style=\"color: blue;\">string<\/span>[] args)<br \/>        {<br \/>            <span style=\"color: green;\">\/\/CREATE THREE NEW DELEGATE INSTANCES<\/span><br \/>            NumDelegate nd;<br \/>            NumDelegate nd1 = <span style=\"color: blue;\">new<\/span> NumDelegate(Add);<br \/>            NumDelegate nd2 = <span style=\"color: blue;\">new<\/span> NumDelegate(Mult);<\/code><\/pre>\n<pre style=\"background-color: white; margin: 0em; overflow: auto;\"><code style=\"color: black; font-family: &quot;consolas&quot; , &quot;courier new&quot; , &quot;courier&quot; , monospace; font-size: 10pt;\">&nbsp;<\/code><\/pre>\n<pre style=\"background-color: white; margin: 0em; overflow: auto;\"><code style=\"color: black; font-family: &quot;consolas&quot; , &quot;courier new&quot; , &quot;courier&quot; , monospace; font-size: 10pt;\">&nbsp;           nd = nd1;  <\/code><code style=\"color: black; font-family: &quot;consolas&quot; , &quot;courier new&quot; , &quot;courier&quot; , monospace; font-size: 10pt;\"><code style=\"color: black; font-family: &quot;consolas&quot; , &quot;courier new&quot; , &quot;courier&quot; , monospace; font-size: 10pt;\"><span style=\"color: green;\">\/\/nd1 PERFORMES Add(5) GIVING 15<\/span><\/code><br \/>            nd = nd + nd2; \/\/nd2 PERFORMS Mult(10) GIVIN 50<br \/><br \/>            <span style=\"color: green;\">\/\/MULTICASTING (EXPLAINED BELOW)<\/span><br \/>            nd(5);<br \/>            Console.WriteLine(<span style=\"color: #a31515;\">\"Value of Num: {0}\"<\/span>, getNum());<br \/>            Console.ReadKey();<br \/>        }<br \/>    }<\/code><\/pre>\n<hr \/>\n<p>In the above code, a delegate is created called NumDelegate that would point to a method that takes an integer parameter.<br \/>In the main program, three delegates are instantiated nd, nd1 and nd2.<br \/>At the end of the program the output would be 65.<br \/>Part 2: Multicast<\/div>\n<\/div>\n","protected":false},"excerpt":{"rendered":"<p>A delegate in C# can be conpared to a function pointer in C and C++. It allows programmers to specify what the funtion to be &hellip; <\/p>\n","protected":false},"author":2,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"_mi_skip_tracking":false,"_monsterinsights_sitenote_active":false,"_monsterinsights_sitenote_note":"","_monsterinsights_sitenote_category":0},"categories":[363,414],"tags":[],"_links":{"self":[{"href":"https:\/\/kindsonthegenius.com\/blog\/wp-json\/wp\/v2\/posts\/164"}],"collection":[{"href":"https:\/\/kindsonthegenius.com\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/kindsonthegenius.com\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/kindsonthegenius.com\/blog\/wp-json\/wp\/v2\/users\/2"}],"replies":[{"embeddable":true,"href":"https:\/\/kindsonthegenius.com\/blog\/wp-json\/wp\/v2\/comments?post=164"}],"version-history":[{"count":1,"href":"https:\/\/kindsonthegenius.com\/blog\/wp-json\/wp\/v2\/posts\/164\/revisions"}],"predecessor-version":[{"id":1436,"href":"https:\/\/kindsonthegenius.com\/blog\/wp-json\/wp\/v2\/posts\/164\/revisions\/1436"}],"wp:attachment":[{"href":"https:\/\/kindsonthegenius.com\/blog\/wp-json\/wp\/v2\/media?parent=164"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/kindsonthegenius.com\/blog\/wp-json\/wp\/v2\/categories?post=164"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/kindsonthegenius.com\/blog\/wp-json\/wp\/v2\/tags?post=164"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}