Coffeehouse Post

Single Post Permalink

View Thread: Anders Interview next week: Ask Questions Here
  • User profile image
    mikebmcl

    Has the C# language team ever considered or would they consider adding a way to use custom logic with automatically implemented properties? As an example, I often find myself creating private fields that I don't particularly care about (and which I don't actually want to be accessible at all) just so I can implement a lock in a property or add some other code (e.g. updating another property when a condition is met) that I don't think merits a method. It would be really nice to be able to do away with those private fields and all of the errors they can introduce and just use a field that would be automatically generated by the compiler instead. Something along the lines of this:

    // In this example, the hypothetical contextual keywords
    // autoget and autoset would allow the token 'field' to 
    // become a contextual keyword. The keyword 'field' would
    // give access to a backing field which would be automatically
    // generated by the compiler for the property.
    
    private static readonly object _amountLock = new object();
    
    public static double Amount
    {
        autoget
        {
            lock (_amountLock)
            {
                return field;
            }
        }
        autoset
        {
            lock (_amountLock)
            {
                field = value;
            }
        }
    }

    -Mike