How to raise an event on a private member (VB.NET)

G

Guest

I constructed a new Class with some private members.
I would like an event to be raised on the moment the value of one of those
private members is changed.
How do I define an event for that private member and how do I raise the event?
 
M

Matt F

If I understand correctly, you want to publicly raise an event when a value
of a private property changes.

You can declare the the event publicly, then in the set statement, raise
that event --- then handle the publicly raised event.

Take a look at the RaiseEvent, AddHandler and possibly RemoveHandler
methods:
RaiseEvent http://msdn2.microsoft.com/en-us/library/fwd3bwed(vs.80).aspx
AddHandler http://msdn2.microsoft.com/en-us/library/7taxzxka(VS.80).aspx
RemoveHandler http://msdn2.microsoft.com/en-us/library/3xz97kac(VS.80).aspx

If I've misunderstood what you're looking for, let us know.
 
G

Guest

Thanks Matt,

What I actualy want to happen is that when the value of a private member of
a class in changed (e.g. via it's property) it automaticaly raises an event.
The event is not explicitly risen through the RaiseEvent command.

Private m_Amount As Long

Public Property Amount() As Long
Get
Return m_Amount
End Get
Set(ByVal Value As Long)
m_Amount = Value
End Set
End Property

Public Sub m_Amount_ValueChanged (ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles m_Amount.ValueChanged
Try
...
Catch ex As Exception
...
Finally
...
End Try
End Sub


When in the code somewhere is executed e.g.:

Amount += 1

increasing the value of m_Amount with 1, the sub m_Amount_ValueChanged
should be executed automaticaly
 
M

Matt F

What I'm suggestiong is kind of a hack-ish work around type thing ----
always something to avoid, but the only way I can think of to handle what
you want. That doesn't mean there isn't something else out there, just
throwing in my two cents here.

Essentially, I'm saying use the code you have below, but (and this is the
bad part) you have to remember to never set the value of m_amount directly
in the class, but rather always set it through Amount. Then in your set,
call RaiseEvent. One way I can think of to enforce not setting m_amount
directly is to declare it as a different type and then convert in the
property set/get --- this is all pretty hack-ish. Another, much cleaner
option is to create a small class that contains a property of Amount,
declare the class as private, raise the event in the sub-class, handle the
class declared in and pass it on up the chain.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top