Reputation: 103447
In c#, I can do this:
public int Foo { get; set; }
Which is nice. But as soon as I want to do anything in the getter or setter, I have to change it to this:
private int foo;
public int Foo {
get { return foo; }
set {
foo = value;
DoSomething(); // all that other code, just to add this line!
}
}
Is it possible to avoid this? I would love to be able to do something like this:
public int Foo {
get;
set {
DoSomething();
}
}
How close can I get to the above?
Upvotes: 1
Views: 829
Reputation: 131112
As others have said, there is no builtin way to do this.
You could achieve something kind of similar with PostSharp. But I'm not sure its worth the effort.
[AfterSet(DoSomething)]
public int Foo {
get;
set;
}
Upvotes: 2
Reputation: 103740
The short answer? No. The long answer? Sorry, still no. :) I feel your pain man, but that's the way it is.
Upvotes: 0
Reputation: 36239
With automatic properties, the compiler generates a backing field for you. A custom getter/setter requires that you manually create a backing field to work with. The ability to specify a custom getter/setter on an automatic property would essentially make it act just like a method, since there's nothing to get or set.
Upvotes: 0
Reputation: 9855
No, there's no way to do this with properties in an existing version of C#, or C# 4.0.
Upvotes: 6