How to raise an event when object created

598 views Asked by At

Why event handler dose not respond to the event when the object created
when I tried to raise a private event at the same way the private event raised and handled as expected

Public Class Form1
    Dim WithEvents nClass As Class1
    Private Sub nClass_Created(ByVal sender As Object, ByVal e As System.EventArgs) Handles nClass.Created
        MessageBox.Show("Created !")
    End Sub

    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        nClass = New Class1
    End Sub
End Class

Public Class Class1
    Event Created(ByVal sender As Object, ByVal e As EventArgs)
    Sub New()
        'some codes

        'when finish
        RaiseEvent Created(Me, New EventArgs)
    End Sub
End Class
1

There are 1 answers

2
Caius Jard On

This concept is broken, logically. In order to raise an event, there has to be an event handler attached to the event. In order to attach a handler, the object has to exist. In order to exist the constructor must complete. You'll never be able to have a constructor raise an event because the delegate list will be empty when the constructor is running (no handlers will have been added)

This would be easier to see in C#, this is how we attach events to things:

var thing = new Thing();
thing.Event += new EventHandler(NameOfSomeMethod);

VB has a similar construct:

Dim thing as New Thing()
AddHandler(thing.Event, AddressOf(NameOfSomeMethod))

As you can see, the thing has to be constructed first. The constructor code could certainly invoke the event, but there won't be any handlers attached so nothing will happen

If you want to get notified every time an object is created use a Factory pattern; the class that constructs your class can raise the event that the class has been created