anaval anaval - 8 months ago 24
Vb.net Question

c# creating events without delegates like VB.net

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.

Answer

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 the Event 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)