473,396 Members | 1,702 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,396 software developers and data experts.

Delegates when to use

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
Jun 27 '08 #1
2 1214
On Jun 20, 5:32*am, "tshad" <t...@dslextreme.comwrote:
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
Jun 27 '08 #2
On Jun 20, 9:32*am, "tshad" <t...@dslextreme.comwrote:
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
Jun 27 '08 #3

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

4
by: Stephen | last post by:
I am new to C# and can't get my head round what delegates are and what they are for. can anyone enlighten me?
4
by: LP | last post by:
Hello! I am still transitioning from VB.NET to C#. I undertand the basic concepts of Delegates, more so of Events and somewhat understand AsyncCallback methods. But I need some clarification on...
4
by: AMDRIT | last post by:
I am trying to understand Delegates and where/when to use them. I can see one potential use of a delegate (on form closing, set the cancel property in the event arguments.) Does anyone have a...
6
by: =?Utf-8?B?Sko=?= | last post by:
I have a logger component that logs to multiple sources, ie textfile, eventlog etc. and I have two methods that depending on where I call up my logger comp. one of them will be called. For ex. if...
6
by: =?Utf-8?B?T2xkQ2FEb2c=?= | last post by:
My question is regarding the use of delegates in C#. I see how .Net uses delegates to wire event handlers to events. It’s an object created by a single line of code by the system and that makes...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.