views:

225

answers:

4

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?

+5  A: 

No, there's no way to do this with properties in an existing version of C#, or C# 4.0.

Dustin Campbell
A: 

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.

David Brown
A: 

The short answer? No. The long answer? Sorry, still no. :) I feel your pain man, but that's the way it is.

BFree
+1  A: 

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;
}
Sam Saffron
Interesting, but I think you're right - it's not worth the effort :P
Blorgbeard