Delegates when to use


T

tshad

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
 
Ad

Advertisements

J

Jon Skeet [C# MVP]

I am still trying to find out why to use a delegate and when it is overkill.

 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
 
D

Duggi

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
 
Ad

Advertisements

T

tshad

Duggi said:
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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top