C# properties: how to use custom set property without private field?

C#Properties

C# Problem Overview


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
    }
}

C# Solutions


Solution 1 - C#

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

Solution 2 - C#

You can try something like this:

public string Name { get; private set; }
public void SetName(string value)
{
    DoSomething();
    this.Name = value;
}

Solution 3 - C#

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

Solution 4 - C#

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;
    }
}

Solution 5 - C#

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.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionPeterdkView Question on Stackoverflow
Solution 1 - C#BrokenGlassView Answer on Stackoverflow
Solution 2 - C#Artur BrutjanView Answer on Stackoverflow
Solution 3 - C#FemarefView Answer on Stackoverflow
Solution 4 - C#Colin BanburyView Answer on Stackoverflow
Solution 5 - C#Jeff YatesView Answer on Stackoverflow