views:

1092

answers:

6

I'd 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)

+13  A: 

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

John Sheehan
+1  A: 

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.

Joseph Daigle
+1  A: 

no you can't: 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 explicity.

stefano m
A: 

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.

Justin Rudd
+1  A: 

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;
Mark Cidade
+1  A: 

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! :)

TcKs