Hi,
I'm kind of new to this as I'm a student. Probably this question is very basic for most of you, but here we go. I've been reading about delagates today and what I understand about them is the following:
1- Delegates can access methods at run time.
2- Delegates are similar to interfaces, but not quite.
Now, if some of you could explain to me in simple words how a delegates access methods at run time and why this is an advantage for a developer, I'd be very grateful.
NOTE: I've been reading the book for the exam 70-315 and it is just very hard to understand.
Thanks a lot,
Eduardo
Satyapriya NayakPosted Dec 1, 2011, 5:47 AM
Hi Eduardo,
Delegates: - It is a procedure pointer, which stores the memory address of another procedure.
Ex:-
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public delegate void abhisek(int x, int y);
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
abhisek a = null;
a = rajiv;
a.Invoke(10, 20);
}
public void rajiv(int x, int y)
{
int z = 0;
z = x + y;
MessageBox.Show(z.ToString());
}
}
}
Thanks
Pathum FernandoPosted Dec 1, 2011, 4:25 AM
For more Read this article,
http://www.pathumf.blogspot.com/2011/11/delegates-in-c.html
Eduardo AriasPosted Dec 3, 2007, 4:29 PM
Thank you for your time. This is very interesting. So, the delagate would be a kind of "middle man" between the two methods you are talking about ... is this correct?
So, in the example you are giving me, Couldn't I just use a method with if-else or a switch statement to identify the iformation coming from the port to let's say a GetScannerInformation() for example?
Thanks you,
Eduardo
Ryan AlfordPosted Dec 3, 2007, 4:11 PM
so that you have a serial port open waiting for a barcode scanner to scan something. when something is scanned, it will fire the "receiveData" event for the serial port. however, you would not be able to update the form with the data from the scan because they were started in different threads. so you would use a delegate. the delegate would "delegate" between the main thread and another thread allowing you to set .Text properties on the form.
that's my interpretation from using them.