Syntax relaxation on var
Posted: Wed Mar 05, 2008 1:07 am
Based on feedback, I've relaxed the syntactic restriction that vars start with an underscore (_). This means you can now say:
Note that because the vars are members of the object, you still have to refer to them with a dot. Python programmers will recognize this as a shorter form of "self.x". C# programmers may take some getting use to this. The point (hehe) is to put members in a different "namespace" as local variables. It can make code easier to read, avoid name clashes and should work nicely with Intellisense.
If you forget the leading dot, the compiler will now note that there is a member with the same name in the error message:
Now suppose at some point that you realize you need some code wrapped around that access. You can rename the var and wrap it in a property like so:
In all the places you wrote ".x" the property will now be accessed with no additional edits required on your part.
There are some disadvantages to vars over properties. Some of the .NET library classes are property-centric including PropertyGrid and DataGridView, which will not look at vars but will look at properties. Also, if you're vending out a library, you'll want to stick with protected or private vars wrapped by public properties.
As usual, you can get the latest code at http://cobra-language.com/source/
class Point
var x as int
var y as int
get isPositive as bool
return .x > 0 and .y > 0
class Program
def main is shared
p = Point()
p.x = 1
assert p.y == 0
Note that because the vars are members of the object, you still have to refer to them with a dot. Python programmers will recognize this as a shorter form of "self.x". C# programmers may take some getting use to this. The point (hehe) is to put members in a different "namespace" as local variables. It can make code easier to read, avoid name clashes and should work nicely with Intellisense.
If you forget the leading dot, the compiler will now note that there is a member with the same name in the error message:
- Code: Select all
Unknown identifier: "x". There is a member named "x" with a similar name that you can access with a leading period (".").
Now suppose at some point that you realize you need some code wrapped around that access. You can rename the var and wrap it in a property like so:
- Code: Select all
var _x as int
get x as int
print 'Accessing x'
return _x
In all the places you wrote ".x" the property will now be accessed with no additional edits required on your part.
There are some disadvantages to vars over properties. Some of the .NET library classes are property-centric including PropertyGrid and DataGridView, which will not look at vars but will look at properties. Also, if you're vending out a library, you'll want to stick with protected or private vars wrapped by public properties.
As usual, you can get the latest code at http://cobra-language.com/source/