Search code examples
c#propertiesautomatic-properties

Can I create an automatic property (no private member) with get and set code?


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?


Solution

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