Delegates and Events
-
I am trying to understand delegates and events in C Sharp. I am finding the subject confusing. Please consider the following program:
using System; using System.Collections.Generic; using System.Linq; using System.Text; public class StockArgs : EventArgs { public StockArgs( String symbol, string price, int volume ) { this.symbol = symbol; this.price = Decimal.Parse(price); this.volume = volume; } public string Symbol { get { return symbol; } } public string Price { get { return Price; } } private string symbol; private decimal price; private int volume; } public class Stock { public delegate void StockPiraceAlertHandler( object source, StockArgs a); public event StockPiraceAlertHandler OnAlert; public delegate void VolumeAlertHandler(object source, StockArgs a); public event VolumeAlertHandler OnVolumeAlert; public void Alert() { if ( OnAlert != null ) OnAlert( this, new StockArgs("ORCL", "14.50", 100000) ); } } public class Main { public static void Main() { Stock stock1 = new Stock(); stock1.OnAlert(null, null); } }
In the main routine (called Main) I want to trigger the alert called OnAlert. However, the code does not compile. Furthermore, the compiler error message implies that alerts can be only generated by the class that defines the alert. If that is true, then it seems like a major deficiency with alerts in C sharp. However, I suspect I am missing one or more key points. Please enlighten me. I thank the group in advance for their responses. Bob -
I am trying to understand delegates and events in C Sharp. I am finding the subject confusing. Please consider the following program:
using System; using System.Collections.Generic; using System.Linq; using System.Text; public class StockArgs : EventArgs { public StockArgs( String symbol, string price, int volume ) { this.symbol = symbol; this.price = Decimal.Parse(price); this.volume = volume; } public string Symbol { get { return symbol; } } public string Price { get { return Price; } } private string symbol; private decimal price; private int volume; } public class Stock { public delegate void StockPiraceAlertHandler( object source, StockArgs a); public event StockPiraceAlertHandler OnAlert; public delegate void VolumeAlertHandler(object source, StockArgs a); public event VolumeAlertHandler OnVolumeAlert; public void Alert() { if ( OnAlert != null ) OnAlert( this, new StockArgs("ORCL", "14.50", 100000) ); } } public class Main { public static void Main() { Stock stock1 = new Stock(); stock1.OnAlert(null, null); } }
In the main routine (called Main) I want to trigger the alert called OnAlert. However, the code does not compile. Furthermore, the compiler error message implies that alerts can be only generated by the class that defines the alert. If that is true, then it seems like a major deficiency with alerts in C sharp. However, I suspect I am missing one or more key points. Please enlighten me. I thank the group in advance for their responses. BobHi Bob, When your Main (or any other code) wants to do something to stock1, it should set one of its properties, or call one of its methods. events are meant to be used the other way around; they exist for the external world (Main) to be signaled by something that happens inside your class (Stock), as in:
class MyForm : Form {
public MyForm() {
Button btn=new Button();
this.Controls.Add(btn);
btn.Click+=new EventHandler(myClickHandler);
...
public void myClickHandler(object sender, EventArgs e) {
// whatever this form wants to happen when the button detects it is being clicked
}
}and the Button class would contain something like:
if (a click got detected) { if (this.Click!=null) this.Click(this, new EventArgs()); // execute all the delegates that were // added to the Click event }
so it is Button who executes its own event, and MyForm who subscribed to it by adding its myClickHandler to the public event. And all this holds true for .NET, not just for C#. :)
Luc Pattyn [Forum Guidelines] [My Articles]
I only read code that is properly indented, and rendered in a non-proportional font; hint: use PRE tags in forum messages
-
I am trying to understand delegates and events in C Sharp. I am finding the subject confusing. Please consider the following program:
using System; using System.Collections.Generic; using System.Linq; using System.Text; public class StockArgs : EventArgs { public StockArgs( String symbol, string price, int volume ) { this.symbol = symbol; this.price = Decimal.Parse(price); this.volume = volume; } public string Symbol { get { return symbol; } } public string Price { get { return Price; } } private string symbol; private decimal price; private int volume; } public class Stock { public delegate void StockPiraceAlertHandler( object source, StockArgs a); public event StockPiraceAlertHandler OnAlert; public delegate void VolumeAlertHandler(object source, StockArgs a); public event VolumeAlertHandler OnVolumeAlert; public void Alert() { if ( OnAlert != null ) OnAlert( this, new StockArgs("ORCL", "14.50", 100000) ); } } public class Main { public static void Main() { Stock stock1 = new Stock(); stock1.OnAlert(null, null); } }
In the main routine (called Main) I want to trigger the alert called OnAlert. However, the code does not compile. Furthermore, the compiler error message implies that alerts can be only generated by the class that defines the alert. If that is true, then it seems like a major deficiency with alerts in C sharp. However, I suspect I am missing one or more key points. Please enlighten me. I thank the group in advance for their responses. BobFor triging event in C# you have to do more like :
public static void Main() { Stock stock1 = new Stock(); //Add "listener" to you event stock1.OnAlert += new Stock.StockPiraceAlertHandler(stock1_OnAlert); // test your event by doing this stock1.Alert(); } //When the Alert event will be fired, this function will be called. static void stock1_OnAlert(object source, StockArgs a) { // Put your triger logic here }
-
I am trying to understand delegates and events in C Sharp. I am finding the subject confusing. Please consider the following program:
using System; using System.Collections.Generic; using System.Linq; using System.Text; public class StockArgs : EventArgs { public StockArgs( String symbol, string price, int volume ) { this.symbol = symbol; this.price = Decimal.Parse(price); this.volume = volume; } public string Symbol { get { return symbol; } } public string Price { get { return Price; } } private string symbol; private decimal price; private int volume; } public class Stock { public delegate void StockPiraceAlertHandler( object source, StockArgs a); public event StockPiraceAlertHandler OnAlert; public delegate void VolumeAlertHandler(object source, StockArgs a); public event VolumeAlertHandler OnVolumeAlert; public void Alert() { if ( OnAlert != null ) OnAlert( this, new StockArgs("ORCL", "14.50", 100000) ); } } public class Main { public static void Main() { Stock stock1 = new Stock(); stock1.OnAlert(null, null); } }
In the main routine (called Main) I want to trigger the alert called OnAlert. However, the code does not compile. Furthermore, the compiler error message implies that alerts can be only generated by the class that defines the alert. If that is true, then it seems like a major deficiency with alerts in C sharp. However, I suspect I am missing one or more key points. Please enlighten me. I thank the group in advance for their responses. BobThe Main class should not tell the Stock class to raise its event. It can be done, but it's not a good design. Usually we see this error when a derived class tries to raise the event of a base class; I've never seen anyone try to do what you are trying to do.
-
I am trying to understand delegates and events in C Sharp. I am finding the subject confusing. Please consider the following program:
using System; using System.Collections.Generic; using System.Linq; using System.Text; public class StockArgs : EventArgs { public StockArgs( String symbol, string price, int volume ) { this.symbol = symbol; this.price = Decimal.Parse(price); this.volume = volume; } public string Symbol { get { return symbol; } } public string Price { get { return Price; } } private string symbol; private decimal price; private int volume; } public class Stock { public delegate void StockPiraceAlertHandler( object source, StockArgs a); public event StockPiraceAlertHandler OnAlert; public delegate void VolumeAlertHandler(object source, StockArgs a); public event VolumeAlertHandler OnVolumeAlert; public void Alert() { if ( OnAlert != null ) OnAlert( this, new StockArgs("ORCL", "14.50", 100000) ); } } public class Main { public static void Main() { Stock stock1 = new Stock(); stock1.OnAlert(null, null); } }
In the main routine (called Main) I want to trigger the alert called OnAlert. However, the code does not compile. Furthermore, the compiler error message implies that alerts can be only generated by the class that defines the alert. If that is true, then it seems like a major deficiency with alerts in C sharp. However, I suspect I am missing one or more key points. Please enlighten me. I thank the group in advance for their responses. BobStock
class owns those events.Main
is just a subscriber who will get notification when the event occurs. To get event notification, you need to subscribe to it first.public static void Main()
{
Stock stock1 = new Stock();
stock1.OnAlert += AlertOccured; // Subscribing event.
stock1.Alert(); // This will callAlert()
method which will triggerOnAlert
event.
}private void AlertOccured(object source, StockArgs a)
{
// your code.
}Delegates are the backbone of events. The main difference is events can be raised only by the class which declares them where a delegate instance can be invoked by anyone who have access to it. Following example shows what I meant.
public delegate void ADelegate();
class Foo
{
public ADelegate ADelegateInstance;public void FireADelegate() { if (ADelegateInstance != null) ADelegateInstance(); }
}
class Program
{
static void AMethod()
{
Console.WriteLine("AMethod()");
}static void Main(string\[\] args) { Foo f = new Foo(); f.ADelegateInstance += AMethod; f.ADelegateInstance(); // This is valid and calls AMethod }
}
Now if you change
public ADelegate ADelegateInstance
topublic event ADelegate ADelegateInstance
the code won't compile.f.ADelegateInstance()
is invalid here. If you are following the standardvoid method(object, EventArgs)
pattern for events, you don't have to create your own delegates. Use theEventHandler<T>
provided with framework. Your code can be written like,public class Stock {
public event EventHandler<StockArgs> OnAlert; public event EventHandler<StockArgs> OnVolumeAlert; public void Alert() { if ( OnAlert != null ) OnAlert( this, new StockArgs("ORCL", "14.50", 100000) ); }
}
:)
Best wishes, Navaneeth
-
Stock
class owns those events.Main
is just a subscriber who will get notification when the event occurs. To get event notification, you need to subscribe to it first.public static void Main()
{
Stock stock1 = new Stock();
stock1.OnAlert += AlertOccured; // Subscribing event.
stock1.Alert(); // This will callAlert()
method which will triggerOnAlert
event.
}private void AlertOccured(object source, StockArgs a)
{
// your code.
}Delegates are the backbone of events. The main difference is events can be raised only by the class which declares them where a delegate instance can be invoked by anyone who have access to it. Following example shows what I meant.
public delegate void ADelegate();
class Foo
{
public ADelegate ADelegateInstance;public void FireADelegate() { if (ADelegateInstance != null) ADelegateInstance(); }
}
class Program
{
static void AMethod()
{
Console.WriteLine("AMethod()");
}static void Main(string\[\] args) { Foo f = new Foo(); f.ADelegateInstance += AMethod; f.ADelegateInstance(); // This is valid and calls AMethod }
}
Now if you change
public ADelegate ADelegateInstance
topublic event ADelegate ADelegateInstance
the code won't compile.f.ADelegateInstance()
is invalid here. If you are following the standardvoid method(object, EventArgs)
pattern for events, you don't have to create your own delegates. Use theEventHandler<T>
provided with framework. Your code can be written like,public class Stock {
public event EventHandler<StockArgs> OnAlert; public event EventHandler<StockArgs> OnVolumeAlert; public void Alert() { if ( OnAlert != null ) OnAlert( this, new StockArgs("ORCL", "14.50", 100000) ); }
}
:)
Best wishes, Navaneeth
You have explained such better than me ! :-D
-
You have explained such better than me ! :-D
Thanks :thumbsup:
Best wishes, Navaneeth