Custom Event (is it possible!)

Armjamil

New member
Joined
Nov 8, 2005
Messages
4
Programming Experience
1-3
I don't know if this is even possible, but let me throw this at you anyways. Maybe you guys can figure something out.

I have a Public variable (bool) and I want it to raise an event anytime its value is changed. I googled this issue but couldn't find anything useful.

Any thoughts?

Thanks in advance.
 
One way would be to create an event and a method to change the variable instead of changin it directly. In the method Raise the event after changing the variable.
VB.NET:
Public someVariable As Boolean
Public Event variableChanged()
Public Sub ChangeVariable(ByVal newValue As Boolean)
    someVariable = newValue
    RaiseEvent variableChanged()
End Sub
 
The usual way to approach this is basically what Paszt suggested, but with a property rather than a public variable and a method:
VB.NET:
Private myVariable As Boolean
Public Event MyPropertyChanged()
Public Property MyProperty() As Boolean
    Get
        Return Me.myVariable
    End Get
    Set(ByVal Value As Boolean)
        Dim previousValue As Boolean = Me.myVariable

        Me.myVariable = Value

        If Me.myVariable <> previousValue Then
            RaiseEvent MyPropertyChanged
        End If
    End Set
End Property
Have a look through the .NET Framework and you'll see that there are very few variables exposed directly. It is almost universally through properties and almost every event is associated with one of those property values changing.
 
Back
Top