C
C#2y ago
CrosRoad95

❔ Listening for object properties changed

let's say i have a object:
class Foo
{
public int Counter {get;set;}
}
class Foo
{
public int Counter {get;set;}
}
i would like to attach an event listener automatically for its all properties so if i do foo.Counter++; some method will invoked without manually adding code to every property
10 Replies
TheRanger
TheRanger2y ago
class Foo
{
private int _counter;
public int Counter
{
get => _counter;
set {
_counter = value;
OnCounterChanged();
}
}

private void OnCounterChanged()
{
// fire your event listener
}
}
class Foo
{
private int _counter;
public int Counter
{
get => _counter;
set {
_counter = value;
OnCounterChanged();
}
}

private void OnCounterChanged()
{
// fire your event listener
}
}
your only way afaik
CrosRoad95
CrosRoad952y ago
i want to avoid this
TheRanger
TheRanger2y ago
i dont think that's possible
CrosRoad95
CrosRoad952y ago
DoSomething(new Foo(), name => {
Console.WriteLine("Property: " + name + " has changed")
})
DoSomething(new Foo(), name => {
Console.WriteLine("Property: " + name + " has changed")
})
i need it to get delta change between previous and current state of object these data i want to send across network so i want to avoid sending data that has not changed the idea is to get know which properties changed and send only these which changed
TheRanger
TheRanger2y ago
well you can probably do it with some system reflection shenanigans
CrosRoad95
CrosRoad952y ago
perhaps i could store old value as hashcode and then compare them has a different idea, make a method to change state, ChangeState(x => x.Counter, 2)
TheRanger
TheRanger2y ago
yeah that could work
CrosRoad95
CrosRoad952y ago
ChangeState(x => x.Counter, 2);
ChangeState(x => x.Counter, 3);
ChangeState(x => x.Counter, 4);
ChangeState(x => x.Counter, 2);
ChangeState(x => x.Counter, 3);
ChangeState(x => x.Counter, 4);
"changeState" will know Counter change, it will immediately schedule a task to update client state but if another state change in next 10ms then cancel previous synchronization, that way 3 changes of same property will yield a single update
333fred
333fred2y ago
Is this a viewmodel for some ui? Because it sounds like what you want is INotifyPropertyChanged and CommunityToolkit.Mvvm, which has source generators to generate the boilerplate for you
Accord
Accord2y ago
Was this issue resolved? If so, run /close - otherwise I will mark this as stale and this post will be archived until there is new activity.