Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# what is the shortest way ( least amount of text ) to attach a function to a property setter?

Tags:

c#

properties

I have a class, that needs to call a refresh function every time a property is changed. So I find myself writing a lot of these:

private double _x;
public double X
    {
        get { return _x; }
        set
        {
            _x = value;
            refresh();
        }
    }

The refresh function is always the same for each property. Is there a shorter way to do this?

Also, I always access the private double _x through double X, so something like public double X { get; set} would work fine, if I could integrate the refresh() method somehow.

like image 673
Philipp Avatar asked Nov 29 '25 14:11

Philipp


1 Answers

The pure C# way is to move the repetitive code to a method.

In your case, something like this:

void Set<T>(ref T field, T value)
{
    field = value;
    refresh();
}

and the use it like this:

private double _x;
public double X { get { return _x; } set { Set(ref _x, value); } }
like image 93
Ivan Stoev Avatar answered Dec 01 '25 04:12

Ivan Stoev