Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

Basic Understanding for Delegate Code

0.00/5 (No votes)
11 Feb 2010 1  
How to code for Delegate In this artical explains basic understanding for delegate and how to create nad use delegate. This code for .net framework for C# This artical is usefull...


How to code for Delegate



In this artical explains basic understanding for delegate and how to create nad
use delegate.



This code for .net framework for C#



This artical is usefull for .net(C#) developers who requires basic understanding
for delegate concept



Using the code



Delegate is a class that can hold a reference to a method or a function. Delegate
class has a signature and it can only reference those methods whose signature is
compliant with the class. Delegates are type-safe functions pointers or callbacks



Below is the code for delegates


delegate int CalculateArea();
delegate int CalculateAreaParam(<span
    class="code-keyword">int</span> i, int j);
public void CallDelegate()
{
    CalculateArea CallMethod = new CalculateArea(Calculate);
    Response.Write(CallMethod.Invoke());
}
public int Calculate()
{
    return 5 * <span
        class="code-digit">4</span>;
}
public void CallDelegateParam(<span
    class="code-keyword">int</span> i, int j)
{
    CalculateAreaParam CallMethod = new CalculateAreaParam(CalculateParam);
    Response.Write(CallMethod.Invoke(i, j));
}
public int CalculateParam(<span
    class="code-keyword">int</span> i, int j)
{
    return i * j;
}




As above code we have created two delegate CalculateArea and CalculateAreaParam.One
is without any parameter and other one is with paramter.



In this code In this method CallDelegate, we have created object for CalculateArea.
This object is initated by Calculate . Once we invoke this object it will calculate
method. Here we have created anther delegate CalculateAreaParam which is with parameter
so while invoking this method we need to pass relavant parameter so it will call
appropriate iniated methods.



License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here