Question

I would like to know if there is any way to add custom behaviour to the auto property get/set methods.

An obvious case I can think of is wanting every set property method to call on any PropertyChanged event handlers as part of a System.ComponentModel.INotifyPropertyChanged implementation. This would allow a class to have numerous properties that can be observed, where each property is defined using auto property syntax.

Basically I'm wondering if there is anything similar to either a get/set template or post get/set hook with class scope.

(I know the same end functionality can easily be achieved in slightly more verbose ways - I just hate duplication of a pattern)

Was it helpful?

Solution

No, you'll have to use "traditional" property definitions for custom behavior.

OTHER TIPS

No you cannot : auto property are a shortcut for an explicit accessor to a private field. e.g.

public string Name { get; set;} 

is a shortcut to

private string _name;
public string Name { get { return _name; } set { _name = value; } };

If you want to put custom logic you must write get and set explicitly.

Look to PostSharp. It is a AOP framework for typicaly issue "this code pattern I do hunderd time a day, how can I automate it?". You can simplify with PostSharp this ( for example ):

public Class1 DoSomething( Class2 first, string text, decimal number ) {
    if ( null == first ) { throw new ArgumentNullException( "first" ); }
    if ( string.IsNullOrEmpty( text ) ) { throw new ArgumentException( "Must be not null and longer than 0.", "text" ) ; }
    if ( number < 15.7m || number > 76.57m ) { throw new OutOfRangeArgumentException( "Minimum is 15.7 and maximum 76.57.", "number"); }

    return new Class1( first.GetSomething( text ), number + text.Lenght );
}

to

    public Class1 DoSomething( [NotNull]Class2 first, [NotNullOrEmpty]string text, [InRange( 15.7, 76.57 )]decimal number ) {
        return new Class1( first.GetSomething( text ), number + text.Lenght );
}

But this is not all! :)

If it's a behavior you'll repeat a lot during development, you can create a custom code snippet for your special type of property.

You could consider using PostSharp to write interceptors of setters. It is both LGPL and GPLed depending on which pieces of the library you use.

The closest solution I can think of is using a helper method:

public void SetProperty<T>(string propertyName, ref T field, T value)
 { field = value;
   NotifyPropertyChanged(propertyName);
 }

public Foo MyProperty 
 { get { return _myProperty}
   set { SetProperty("MyProperty",ref _myProperty, value);}
 } Foo _myProperty;
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top