Randy Minder
Randy Minder

Reputation: 48522

C# - Events Question

Can any C# object be set up such that an event can be tied to it to fire when it's value changes? If so, how is this done? For example, let's take a very simple example. Say I have a variable declared as follows:

int i;

Is it possible to create an event that fires any time the value of i changes?

Thanks.

Upvotes: 1

Views: 143

Answers (4)

Jon Skeet
Jon Skeet

Reputation: 1503379

Well, you can't change fields so that events are fired when the value changes.

On the other hand, you can easily make it so that when a property changes, an event is fired. Only the author of the class containing the property can do this, however1 - you can't attach an event to an arbitrary existing class.


1 A slight exception would be a virtual property, which could be overridden solely for the purpose of raising the event. That would be pretty rare though.

Upvotes: 6

Marius Schulz
Marius Schulz

Reputation: 16470

Have a look at the INotifyPropertyChanged interface that can be implemented by a class and called by - at least some of - its properties to notify listeners that some values changed.

Upvotes: 2

Chad
Chad

Reputation: 3237

Take a look at the PropertyChangedEvent pattern.

Upvotes: 0

Kris van der Mast
Kris van der Mast

Reputation: 16613

Another option would be to use the Observer pattern.

Grz, Kris.

Upvotes: 0

Related Questions