129

I want to do this:

public Name
{
    get;
    set
    {
        dosomething();
        ??? = value
    }
}

Is it possible to use the auto-generated private field?
Or is it required that I implement it this way:

private string name;
public string Name
{
    get
    {
        return name;
    }
    set
    {
        dosomething();
        name = value
    }
}
Jeff Yates
  • 61,417
  • 20
  • 137
  • 189
Peterdk
  • 15,625
  • 20
  • 101
  • 140
  • 2
    There is lots of good discussion on this at this SO question: http://stackoverflow.com/questions/1277018/c-3-0-automatic-properties-what-would-be-the-name-of-private-variable-create – David Hall Jan 28 '11 at 22:29

5 Answers5

146

Once you want to do anything custom in either the getter or the setter you cannot use auto properties anymore.

BrokenGlass
  • 158,293
  • 28
  • 286
  • 335
46

You can try something like this:

public string Name { get; private set; }
public void SetName(string value)
{
    DoSomething();
    this.Name = value;
}
Artur Brutjan
  • 579
  • 5
  • 7
  • 8
    +1 To my mind this answer rebukes the accepted answer. It is using auto properties. It explicitly sets setter to private. This is a good thing because it lets the end user or developer know there is likely more going on behind the setter method. – ooXei1sh Oct 12 '15 at 20:20
  • What's the difference between this and not having set at all? – Sidhin S Thomas Nov 11 '19 at 16:59
  • 7
    @SidhinSThomas not providing a `private set` would prevent the property from being set by its class's members; it would be strictly read-only. You would only be able to set its data in the constructor. – Bondolin Dec 03 '19 at 13:59
21

As of C# 7, you could use expression body definitions for the property's get and set accessors.

See more here

private string _name;

public string Name
{
    get => _name;
    set
    {
        DoSomething();
        _name = value;
    }
}
Luis Lavieri
  • 4,064
  • 6
  • 39
  • 69
Colin Banbury
  • 857
  • 10
  • 17
17

This is not possible. Either auto implemented properties or custom code.

Femaref
  • 60,705
  • 7
  • 138
  • 176
10

It is required that you implement it fully given your scenario. Both get and set must be either auto-implemented or fully implemented together, not a combination of the two.

Jeff Yates
  • 61,417
  • 20
  • 137
  • 189