Reputation: 1138
My Code in VB.net
Public Class Form1
'step 1. declare the event
Private Event TestEvent(ByVal msg As String)
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
'step 2. raise the event
RaiseEvent TestEvent("Hello World")
End Sub
Private Sub Form1_load()
'step 3. add the event handler
AddHandler Me.TestEvent, AddressOf test_handler
Sub
Private Sub test_handler(ByVal message As String)
MsgBox(message)
End Sub
End Class
My Code in C#
namespace CSharp_Event_Test
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
//step 1. declare delegate of event
private delegate void TestEventHandler(string msg);
//step 2. declare the event
private event TestEventHandler ActualTestEvent;
private void button1_Click(object sender, EventArgs e)
{
//step 3. raise the event
ActualTestEvent("Hello World");
}
private void Form1_Load(object sender, EventArgs e)
{
//step 4. Specify the event handler
this.ActualTestEvent += new TestEventHandler(test_event);
}
private void test_event(string M) {
MessageBox.Show(text: M, caption: "Event Raised");
}
}
}
Both of them work actually. Im just curious why I was able to declare an event in VB even without a delegate but in C# making events without delegate gives me an error.
Upvotes: 1
Views: 1094
Reputation: 1885
See also C# event with custom arguments
class Program
{
public static event Action<string> myEvent;
static void Main(string[] args)
{
myEvent += Program_myEvent1;
myEvent("Cheese");
}
private static void Program_myEvent1(string val)
{
Console.WriteLine(val);
Console.ReadKey();
}
}
The trick is to use Action<T>
instead of EventHandler
Upvotes: 3
Reputation: 36483
Q: I'm just curious why I was able to declare an event in VB even without a delegate but in C# making events without delegate gives me an error.
As explained in this article on delegates, it's because VB.NET is capable of implicitly declaring a delegate type for you when declaring an event:
Although you can create your own delegates, in most cases Visual Basic creates the delegate and takes care of the details for you. For example, an
Event
statement implicitly defines a delegate class named<EventName>EventHandler
as a nested class of the class containing theEvent
statement, and with the same signature as the event.
Unfortunately, C# doesn't provide this convenient syntactic sugar, so you have to explicitly declare the delegate type before declaring the event. (Or, as observed in Adam's answer, you can reuse existing delegate types)
Upvotes: 7