Create/Allow access to a private backing field for a property automatically.

Topics: C# Language Design
May 17, 2014 at 3:53 PM
Edited May 17, 2014 at 4:00 PM
Right now there are two ways to create a property (automatically or manually):
public string FirstName { get; private set; }
private string _firstName;
public string FirstName
{
    get { return _firstName; }
    set { _firstName = value; }
}
What I'd like to see, perhaps through a new keyword, is a way to take advantage of automatic backing fields within manual property creation (Note, I selected the keyword current simply to satisfy my example code):
public string FirstName
{
    get { return current; }
    set { current = value; }
}
This doesn't really look that different from the automatic or manual properties, in fact in my example writing an automatic property would be less code. But, where this will help is when you want to do more than an automatic property allows, but take advantage of the "private, anonymous backing field that can only be accessed through the property's get and set accessors."

Fully-Rolled Out vs New Suggestion:
private string _firstName;
public string FirstName
{
    get { return CustomEncryption.Decrypt(_firstName); }
    set { _firstName = CustomEncryption.Encrypt(value); }
}
public string FirstName
{
    get { return CustomEncryption.Decrypt(current); }
    set { current = CustomEncryption.Encrypt(value); }
}
A nice difference between these two (besides saving one line of code) is that the private backing field is anonymously created, so the rest of the class cannot access the member and change its value without going through my property setter (enforcing it to be encrypted/decrypted appropriately). It's far better than trying to make sure that if anyone changes how the class works internally that they don't set the value of the private backing field manually.

So, what happens if the property does not need a private, anonymous backing field? The compiler would have to know not to create one based on whether or not the keyword is used:

Wrapper Properties (Not created)
private static readonly _customer = new Customer();
public string FirstName
{
    get { return Customer.FirstName; }
    set { Customer.FirstName = value; }
}
Getter Only (Not Created)
public string FullName
{
    get { return String.Format("{0} {1}", Firstname, LastName); }
}
Weird Scenario (Compiler error -- private backing field is never set)
public string FirstName
{
    get { return current; }
    set { DoSomething(value); } // Why isn't current (private backing) being set!?
}
Final caveat: I have no idea how new keywords are chosen in respect to possibly breaking existing code. In my example, anyone that had a private backing field named current would have their code broken. :/
May 17, 2014 at 4:54 PM
I suggested something similar, but using e.g. {get; private readonly var;} or{get; protected var _foo;}` as syntax, and didn't get much response (there's a post on the subject).