18

I want to do something like this:

class Foo
{
    bool Property
    {
        get;
        set
        {
            notifySomethingOfTheChange();
            // What should I put here to set the value?
        }
    }
}

Is there anything I can put there to set the value? Or will I have to explicitly define the get and add another field to the class?

Matt
  • 21,026
  • 18
  • 63
  • 115

4 Answers4

16

You either have a default property, with compiler-generated backing field and getter and/or setter body, or a custom property.

Once you define your own setter, there is no compiler-generated backing field. You have to make one yourself, and define the getter body also.

Ben Voigt
  • 277,958
  • 43
  • 419
  • 720
14

There is no way.

  • You can either have both setter and getter auto-implemented

    bool Property { get; set; }
    
  • Or implement both manually

    bool Property
    {
        get { return _prop; }
        set { _prop = value; }
    }
    
abatishchev
  • 98,240
  • 88
  • 296
  • 433
6

No this is the case where auto-properties are not the best fit, and therefore the point at which you go to proper implemented properties:

class Foo
{
    private bool property;
    public bool Property
    {
        get
        {
            return this.property;
        }
        set
        {
            notifySomethingOfTheChange();
            this.property = value
        }
    }
}
Jamiec
  • 133,658
  • 13
  • 134
  • 193
  • @Cloud it's quite "planely" obvious you're right ;) The accepted answer is basically the same answer, just without code. – Jamiec Feb 11 '19 at 10:24
  • 1
    I feel like that is going to go wright over everyone's heads. – Cloud Feb 11 '19 at 10:34
-3

In many cases you can use the "Auto Property" feature e.g. public int Age { get; set; } = 43;

This is a good reference http://www.informit.com/articles/article.aspx?p=2416187

Naji K.

  • 3
    This does not answer the question. OP is in a situation where they cannot use an auto property, and has already stated so. – BJ Myers Jul 25 '18 at 20:52