This project is read-only.
10
Vote

Private fields scoped to a property

description

With the features being added for properties in C# 6.0, there is one small (I think?) additional feature that would nice to have: fields that are scoped to a property's getter and setter. This would be really nice in cases where you're not using an auto-property and want to control access to a field. Example:
class Foo
{
    public int Bar 
    {
        get
        {
             return _bar;
        }
        set
        {
             _bar = value + 5;
        }
        private int _bar;
    }

    public void Baz() 
    {
        _bar = _bar + 10; //Can't do this! You gotta use the property like everyone else!
    }
}
This provides two benefits: the field _bar can only be accessed via the getter, and the field will always be located near its corresponding property in the source code (refactorings can often make them end up located in different spots).

comments

pzolja wrote Jul 20, 2014 at 7:36 PM

Another way would be to allow us access to the underlying hidden property "value" inside the property get/set blocks. The keyword "value" is already taken, so we'd need a new one. For this purpose I'll call it "property" (sounds nice when reading the code imo). Here's a silly example:
public class Foo
{
    public int Bar
    {
        get { return property + 5; }
        set { property = value - 5; }
    }
}
The default implementation (no blocks for get/set) would be the equivalent of:
public class Foo
{
    public int Bar
    {
        get { return property; }
        set { property = value; }
    }
}