Alternative Simplified C# Property Syntax

Introduction

When I first read about properties in C#, I was a bit excited and a bit confused. I was glad to see so many inventions, including properties, designed to help programmers be more productive. But on the other hand, why do properties require so much typing just to declare a variable? And why does it seem we need to create two variables to do the job of one?

For review, this example shows the minimum syntax to create a property in C#.

class Program
{
    static void Main(string[] args)
    {
        MyClass obj = new MyClass();
        
        // Using the property to get and set values.
        obj.Myval = 42; // Set the value using the setter.
        int value = obj.Myval; // Get the value using the getter.

        Console.WriteLine("Value: " + value); // Output: Value: 42
    }
}

class MyClass
{
    private int myval;

    public int Myval
    {
        get
        {
            return myval;
        }
        set
        {
            myval = value;
        }
    }
}

In my opinion, the problem with the above code is that programmers must declare two identifiers, which are confusingly similar: myval and Myval. You have to remember which one of the two you are allowed to use from outside the class. Of course, for a newbie, it's even more confusing because a third identifier, "value", is used without even being declared. Okay, so you quickly learn that "value" is a keyword, not an identifier. But still, it should be easier than this.

Here is a proposed alternative syntax that accomplishes the same thing and is also extensible.

class Program
{
    static void Main(string[] args)
    {
        MyClass obj = new MyClass();
        // Using the property to set and get values.
        obj.Myval = 42; // Set the value using the setter.
        int value = obj.Myval; // Get the value using the getter.
        Console.WriteLine("Value: " + value); // Output: Value: 42
    }
}
class MyClass
{
    public int Myval { get; set; }
}

The new "property" keyword declares that Myval is an actual variable definition. As a property, the variable is only accessible through the provided getter/setter, which is automatically generated in this case. By giving us an automatic, albeit simplistic, getter/setter, it's like the compiler is saying: "If you cannot afford a getter or a setter, one will be appointed for you." I recall the C language standards committee came up with that bit of levity when they adopted function prototypes. Well, it's about as humorous as we can expect standards bodies to be.

Getting back to the subject, you can see that the simplified syntax reduces the amount of code required and the number of confusingly similar identifiers from three to one.

Well, sort of. We can say three to two, at least. The free setter provided by the compiler, um, isn't very valuable. In fact, we may as well just declare a regular variable as having a property with a free setter. So it's true that the value keyword is still required to implement a real-world setter, but this new style is safer because the class author may not inadvertently violate the variable range rules by bypassing the setter from within other member functions. In other words, having one identifier instead of two avoids the risk of the class author assigning an inappropriate value directly to Myval (not Myval) from other code within the class.

You may say this new syntax seems unusual. Hey man, what do you think everybody says the first time they see a for loop in C/C++/Java/C#? As practical as the for loop is, it also proves the point that the syntax of a language rules! So just as the syntax of an enum is different from that of a struct, the property keyword is similar in that it also establishes special rules for the syntax that follows within the braces.

The automatic (free) getter/setter in the simplified property syntax can be easily extended by replacing either or both with a function, as C# currently requires. But either way, you still have the option to avoid creating an unnecessary identifier for this common programming task. For example.

class Program
{
    static void Main(string[] args)
    {
        MyClass obj = new MyClass();
        try
        {
            obj.Myval = 42; // This will throw an exception due to the custom setter logic.
        }
        catch (Exception ex)
        {
            Console.WriteLine("Exception: " + ex.Message);
        }
        int value = obj.Myval; // Value will be 0 due to the failed assignment.
        Console.WriteLine("Value: " + value); // Output: Value: 0
    }
}
class MyClass
{
    private int _myval;

    public int Myval
    {
        get { return _myval; }
        set
        {
            if (value > 10)
                throw new Exception("Value cannot be greater than 10.");
            else
                _myval = value;
        }
    }
}

I hope the C# community will speak up about this and further refine the concept, so Microsoft and ECMA will consider this for future versions of the language.


Similar Articles