Properties: just like public member variables, except when they aren’t
Sterling Camden
Many object-oriented languages provide an abstraction called properties: data members that belong to a class instance, but whose public interface controls how those members can be manipulated via accessor methods. In languages like C#, VB.NET, and Synergy/DE, the syntax for accessing properties is identical to accessing public member variables. That’s convenient and intuitive – but misleading, because properties are methods, not data.
Usually that distinction has no practical consequences. But just try passing a property as an “out” parameter. Even if the property defines a setter method, the compiler complains “A property or indexer may not be passed as an out or ref parameter”. That means that you can’t even pass an element of an ArrayList to an “out” parameter. You can say:
myarray[0] = some_object;
but you can’t say
FillInTheObject(out myarray[0]);
My first reaction to this restriction was the same as that of BCS: Why doesn’t the compiler just generate a call to the setter method when the function returns?
A couple of potential reasons:
- Unless somehow the setter method could get passed into the exact statement(s) that modifies the parameter, you could introduce timing issues. Another thread (or even a routine in the same thread) that has a reference to the property or the member data behind it could modify that data after the logical modification within the function, but before the function returns.
- Too much syntactic sugar leads to code diabetes. When the compiler does too much for you, you get more overhead than you bargained for.
I’m not sure that either of these objections outweighs Caveat emptor. After all, you currently can’t do this at all, so changing the behavior wouldn’t break any existing code. Unless you’re in the camp that believes that the compiler should slap your hand whenever you do something it thinks you didn’t mean to do. I’m not in that camp.
Why doesn’t Ruby have this problem? After all, it has accessor methods for attributes (the equivalent of properties). The answer is simple: Ruby doesn’t support “out” parameters. Like a good functional language, you must return values as the result of a function, not as an argument. That constrains assignment to a distinct moment in the execution of the function (after it returns), and thereby eliminates the concurrency issue while simultaneously making the assignment apparent to the most casual perusal of the code.
So the real issue here is not that properties look like data while behaving like functions. The real problem is that you shouldn’t use “out” parameters.
Posted in .NET, C#, Ruby, SynergyDE, Visual Basic |
No Comments » RSS 2.0 | Sphere it!



