PC Review


Reply
Thread Tools Rate Thread

Delegates when to use

 
 
tshad
Guest
Posts: n/a
 
      20th Jun 2008
I am still trying to find out why to use a delegate and when it is overkill.

For example:

If I do something like:

**************************************************
using System;
using System.Collections.Generic;
using System.Text;

public delegate double Delegate_Prod(int a, int b);

class Class1
{


static double fn_Prodvalues(int val1, int val2)
{
return val1 * val2;
}
static void Main(string[] args)
{


//Creating the Delegate Instance
Delegate_Prod delObj = new Delegate_Prod(fn_Prodvalues);


Console.Write("Please Enter Values");

int v1 = Int32.Parse(Console.ReadLine());
int v2 = Int32.Parse(Console.ReadLine());

//use a delegate for processing

double res = delObj(v1, v2);
Console.WriteLine("Result :" + res);
Console.ReadLine();

}
}
**************************************************

I understand why this works. But why would you do this if you can just do:

****************************************************
using System;
using System.Collections.Generic;
using System.Text;

public delegate double Delegate_Prod(int a, int b);

class Class1
{


static double fn_Prodvalues(int val1, int val2)
{
return val1 * val2;
}
static void Main(string[] args)
{


//Creating the Delegate Instance
Delegate_Prod delObj = new Delegate_Prod(fn_Prodvalues);


Console.Write("Please Enter Values");

int v1 = Int32.Parse(Console.ReadLine());
int v2 = Int32.Parse(Console.ReadLine());

//use a delegate for processing

double res = fn_Prodvalues(v1, v2); <---------
Console.WriteLine("Result :" + res);
Console.ReadLine();

}
}
****************************************************
Here I do exactly the same thing, except I call the function directly as
opposed to having to set up a delegate, create the instance and then call
it.

If I were looking at this 2nd example what would cause me to think that I
should use a delegate instead and do the 1st example.

I understand the mechanics, but I am trying to see why I should do one over
the other.

Thanks,

Tom


 
Reply With Quote
 
 
 
 
Jon Skeet [C# MVP]
Guest
Posts: n/a
 
      20th Jun 2008
On Jun 20, 5:32*am, "tshad" <t...@dslextreme.com> wrote:
> I am still trying to find out why to use a delegate and when it is overkill.


<snip>

> *Here I do exactly the same thing, except I call the function directly as
> opposed to having to set up a delegate, create the instance and then call
> it.
>
> If I were looking at this 2nd example what would cause me to think that I
> should use a delegate instead and do the 1st example.


You shouldn't. Delegates aren't particularly useful when you know
exactly which method you want to call at the point where you want to
call it.

They're useful like generics - where you can write a routine which
needs to call something but it doesn't particularly care what.
Enumerable.Where is a good example of this: it needs to have something
to call - a predicate - to determine whether or not a given item in
the source iterator should appear in the result iterator.

It doesn't need to know what the predicate does, just that it will
look at an item and return true or false.

If you were writing something like the Where method yourself for some
reason and you already knew what the predicate was, you could put it
in directly. The beauty of the Where method (etc) is that all the
logic *except* the predicate is encapsulated in one place, so you
*only* need to supply the bit that varies (the predicate).

Jon
 
Reply With Quote
 
Duggi
Guest
Posts: n/a
 
      20th Jun 2008
On Jun 20, 9:32*am, "tshad" <t...@dslextreme.com> wrote:
> I am still trying to find out why to use a delegate and when it is overkill.
>
> For example:
>
> If I do something like:
>
> **************************************************
> using System;
> using System.Collections.Generic;
> using System.Text;
>
> public delegate double Delegate_Prod(int a, int b);
>
> class Class1
> {
>
> * * static double fn_Prodvalues(int val1, int val2)
> * * {
> * * * * return val1 * val2;
> * * }
> * * static void Main(string[] args)
> * * {
>
> * * * * //Creating the Delegate Instance
> * * * * Delegate_Prod delObj = new Delegate_Prod(fn_Prodvalues);
>
> * * * * Console.Write("Please Enter Values");
>
> * * * * int v1 = Int32.Parse(Console.ReadLine());
> * * * * int v2 = Int32.Parse(Console.ReadLine());
>
> * * * * //use a delegate for processing
>
> * * * * double res = delObj(v1, v2);
> * * * * Console.WriteLine("Result :" + res);
> * * * * Console.ReadLine();
>
> * * }}
>
> **************************************************
>
> I understand why this works. *But why would you do this if you can justdo:
>
> ****************************************************
> using System;
> using System.Collections.Generic;
> using System.Text;
>
> public delegate double Delegate_Prod(int a, int b);
>
> class Class1
> {
>
> * * static double fn_Prodvalues(int val1, int val2)
> * * {
> * * * * return val1 * val2;
> * * }
> * * static void Main(string[] args)
> * * {
>
> * * * * //Creating the Delegate Instance
> * * * * Delegate_Prod delObj = new Delegate_Prod(fn_Prodvalues);
>
> * * * * Console.Write("Please Enter Values");
>
> * * * * int v1 = Int32.Parse(Console.ReadLine());
> * * * * int v2 = Int32.Parse(Console.ReadLine());
>
> * * * * //use a delegate for processing
>
> * * * * double res = fn_Prodvalues(v1, v2); * * * * ** * * * <---------
> * * * * Console.WriteLine("Result :" + res);
> * * * * Console.ReadLine();
>
> * * }}
>
> ****************************************************
> *Here I do exactly the same thing, except I call the function directly as
> opposed to having to set up a delegate, create the instance and then call
> it.
>
> If I were looking at this 2nd example what would cause me to think that I
> should use a delegate instead and do the 1st example.
>
> I understand the mechanics, but I am trying to see why I should do one over
> the other.
>
> Thanks,
>
> Tom

=============================================================
Good that you tried understanding the delegate concept

See the following code

public delegate double Delegate_Prod(int a, int b);

// My Company is the provider of Exm class
public class Exm
{
public Delegate_Prod delObj = null; // delegate object is
null

public void ProcessMyLogic()
{
Console.Write("Please Enter Values\n");

int v1 = Int32.Parse(Console.ReadLine());
int v2 = Int32.Parse(Console.ReadLine());

double res = 0;

if (delObj != null)
res = delObj(v1, v2); // I do not actually know how
to process the data. The data processing is left to the user of the
class
else
throw new Exception("DataProcessing Logic is not
available");

Console.WriteLine("Result :" + res);
}
}


// Other company uses my class for their development
public class Program
{
static double fn_Prodvalues(int val1, int val2)
{
//class user will decide this logic
return val1 * val2;
}

static double MyOtherLogic(int val1, int val2)
{
//class user will decide this logic
return val1 - val2;
}

public static void Main(string[] args)
{
Exm ex = new Exm();

// ex.delObj = new Delegate_Prod(fn_Prodvalues); // try
uncomment this line and comment next line
ex.delObj = new Delegate_Prod(MyOtherLogic);

ex.ProcessMyLogic();

Console.ReadLine();
}
}
=======================================================================
In this case I will not be bothering about how the data should be
processed, instead I left the choice to the user of my class. This is
the real advantage of delegates.

These are also useful in events


-Cnu
 
Reply With Quote
 
tshad
Guest
Posts: n/a
 
      29th Jun 2008
Duggi wrote:
> On Jun 20, 9:32 am, "tshad" <t...@dslextreme.com> wrote:
>> I am still trying to find out why to use a delegate and when it is
>> overkill.
>>
>> For example:
>>
>> If I do something like:
>>
>> **************************************************
>> using System;
>> using System.Collections.Generic;
>> using System.Text;
>>
>> public delegate double Delegate_Prod(int a, int b);
>>
>> class Class1
>> {
>>
>> static double fn_Prodvalues(int val1, int val2)
>> {
>> return val1 * val2;
>> }
>> static void Main(string[] args)
>> {
>>
>> //Creating the Delegate Instance
>> Delegate_Prod delObj = new Delegate_Prod(fn_Prodvalues);
>>
>> Console.Write("Please Enter Values");
>>
>> int v1 = Int32.Parse(Console.ReadLine());
>> int v2 = Int32.Parse(Console.ReadLine());
>>
>> //use a delegate for processing
>>
>> double res = delObj(v1, v2);
>> Console.WriteLine("Result :" + res);
>> Console.ReadLine();
>>
>> }}
>>
>> **************************************************
>>
>> I understand why this works. But why would you do this if you can
>> just do:
>>
>> ****************************************************
>> using System;
>> using System.Collections.Generic;
>> using System.Text;
>>
>> public delegate double Delegate_Prod(int a, int b);
>>
>> class Class1
>> {
>>
>> static double fn_Prodvalues(int val1, int val2)
>> {
>> return val1 * val2;
>> }
>> static void Main(string[] args)
>> {
>>
>> //Creating the Delegate Instance
>> Delegate_Prod delObj = new Delegate_Prod(fn_Prodvalues);
>>
>> Console.Write("Please Enter Values");
>>
>> int v1 = Int32.Parse(Console.ReadLine());
>> int v2 = Int32.Parse(Console.ReadLine());
>>
>> //use a delegate for processing
>>
>> double res = fn_Prodvalues(v1, v2); <---------
>> Console.WriteLine("Result :" + res);
>> Console.ReadLine();
>>
>> }}
>>
>> ****************************************************
>> Here I do exactly the same thing, except I call the function
>> directly as opposed to having to set up a delegate, create the
>> instance and then call it.
>>
>> If I were looking at this 2nd example what would cause me to think
>> that I should use a delegate instead and do the 1st example.
>>
>> I understand the mechanics, but I am trying to see why I should do
>> one over the other.
>>
>> Thanks,
>>
>> Tom

> =============================================================
> Good that you tried understanding the delegate concept
>
> See the following code
>
> public delegate double Delegate_Prod(int a, int b);
>
> // My Company is the provider of Exm class
> public class Exm
> {
> public Delegate_Prod delObj = null; // delegate object is
> null
>
> public void ProcessMyLogic()
> {
> Console.Write("Please Enter Values\n");
>
> int v1 = Int32.Parse(Console.ReadLine());
> int v2 = Int32.Parse(Console.ReadLine());
>
> double res = 0;
>
> if (delObj != null)
> res = delObj(v1, v2); // I do not actually know how
> to process the data. The data processing is left to the user of the
> class
> else
> throw new Exception("DataProcessing Logic is not
> available");
>
> Console.WriteLine("Result :" + res);
> }
> }
>
>
> // Other company uses my class for their development
> public class Program
> {
> static double fn_Prodvalues(int val1, int val2)
> {
> //class user will decide this logic
> return val1 * val2;
> }
>
> static double MyOtherLogic(int val1, int val2)
> {
> //class user will decide this logic
> return val1 - val2;
> }
>
> public static void Main(string[] args)
> {
> Exm ex = new Exm();
>
> // ex.delObj = new Delegate_Prod(fn_Prodvalues); // try
> uncomment this line and comment next line
> ex.delObj = new Delegate_Prod(MyOtherLogic);
>
> ex.ProcessMyLogic();
>
> Console.ReadLine();
> }
> }
> =======================================================================
> In this case I will not be bothering about how the data should be
> processed, instead I left the choice to the user of my class. This is
> the real advantage of delegates.
>


I see.

I made a small change in the Program class to see what it would do if
MultiCast it and set both delegates before I put in the Console.Write in the
functions, it looked like it only did one function (the last one) as it only
returned one result - which makes sense since there is only one return
value. I assume it passed back both but only kept the last one. When I
added the Console.Write lines:

******************************
class Program
{
static double fn_Prodvalues(int val1, int val2)
{
//class user will decide this logic
Console.WriteLine("In fn_Prodvalues");
return val1 * val2;
}

static double MyOtherLogic(int val1, int val2)
{
//class user will decide this logic
Console.WriteLine("In MyOtherLogic");
return val1 - val2;
}
static void Main(string[] args)
{
Exm ex = new Exm();

ex.delObj = new Delegate_Prod(fn_Prodvalues); // try uncomment
this line and
// comment next
line
ex.delObj += new Delegate_Prod(MyOtherLogic);

ex.ProcessMyLogic();

Console.ReadLine();
}
}
*******************************
I got the following results:
*******************************
Please Enter Values
20
30
In fn_Prodvalues
In MyOtherLogic
Result :-10
*******************************

If I reversed the order of how I set ex.delObj - I get:

************************************
Please Enter Values
20
30
In MyOtherLogic
In fn_Prodvalues
Result :600
************************************

So both delegates get handled but you will only get the last result.

> These are also useful in events


Which is where the MultiCast is useful. Not sure why you would use it in
another place, but I'm sure are good reasons.

Thanks,

Tom
>
>
> -Cnu



 
Reply With Quote
 
 
 
Reply

Thread Tools
Rate This Thread
Rate This Thread:

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are Off


Similar Threads
Thread Thread Starter Forum Replies Last Post
Can we declare delegates in class and can we declare delegates in Interface Bhuwan Bhaskar Microsoft Dot NET Framework 4 4th Oct 2007 05:25 AM
Advanced use of delegates to automatically disconnect delegates from a set of events kristian.freed@gmail.com Microsoft C# .NET 2 18th Nov 2006 09:56 PM
PinvokeDLL or delegates or ??? ... Calling C# delegates from C++ as CALLBACK Roland Rehmnert Microsoft Dot NET Compact Framework 1 20th Feb 2005 12:21 PM
Help with delegates OpticTygre Microsoft VB .NET 2 18th Feb 2005 01:47 PM
Delegates will be the end of me Todd Microsoft C# .NET 2 8th Jul 2004 03:43 PM


Features
 

Advertising
 

Newsgroups
 


All times are GMT +1. The time now is 01:09 AM.