Once more about macros in C#

I am writing a WPF app. In WPF they like very much all kinds of notifications about property changes. Thus, I’ve got a class with a bunch of properties similar to this:

    class Person
    {
        void OnPropertyChanged(string propertyName)
        {
        …
        }
 
        public string LastName
        {
            get { return _lastName; }
 
            set
            {
                if (_lastName != value)
                {
                    _lastName = value;
                    OnPropertyChanged("LastName");
                }
            }
        }
        string _lastName;
 
        public int Age
        {
            get { return _age; }
 
            set
            {
                if (_age != value)
                {
                    _age = value;
                    OnPropertyChanged("Age");
                }
            }
        }
        int _age;
    }

This is long, boring, and bloated. Of course, I created a code snipped for generating the properties, but it works only once, at the time of writing, the code is still bloated, and all the changes must be done by hand. Besides, it is unable to change case automatically, so that Age becomes _age.

I would like to see something like:

    class MyClass
    {
        public Observable<string> LastName;
        public Observable<int> Age;
    }
 
    property Observable<T>
    {
        T _value;
        get { return _value; }
        set
        {
            if (_value != value)
            {
                _value = value;
                OnPropertyChanged(#PropertyName);
            }
        }
    }

Of course, the syntax is approximate. Unfortunately, nothing of the sort exists. Generics are of no help here, and there are no macros in C#.

Posted in

Leave a Reply

Your email address will not be published. Required fields are marked *