Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

Once More About Macros in C#

0.00/5 (No votes)
11 May 2010 1  
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 snippet 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#.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here