Archives

Archives / 2014 / February
  • A C# Feature I’d Really Like to See in a Future Version

    In C#, if you declare a variable somewhere inside curly braces, that variable cannot be accessed from the outside. Examples are (private) member variables inside a class, (local) variables inside functions or statement blocks in general.

    What I really would like to see in a future version of C# are variables that can only be accessed within a property declaration. Then it would be possible to write something like this:

    class MyClass
    {
        public string MyProperty
        {
            string _myProperty; // only accessible from within MyProperty
    
            get
            {
                DoSomething();
                return _myProperty;
            }
            set
            {
                _myProperty=value;
                DoSomethingElse();
            }
        }
    }

    Looks like other people had the same idea, the feature is already suggested on UserVoice. The original author of the suggestion had a different reason for the suggestion (citing documentation requirements); the benefit that I and another commenter see is the additional encapsulation. By declaring the variable the way it is shown above, you could express the intent that the backing field isn’t intended to be accessed directly, helping other people reading the code (or yourself in a couple of weeks…).

    If you agree that the feature would be a valuable addition to the C# language, it would be nice if you could vote for it on UserVoice.