Friday, March 04, 2005

Delphi and Global Variables

Something that is interesting about Delphi and global variables is there is no such thing.

A global variable is one that is accessible everywhere, you actually cannot do that directly in a Delphi project of any complexity. Turbo Pascal was one of the first languages to introduce name spaces, in I believe version 3, with the concept of units. A unit limits the scope of all your variables to that unit and any unit that uses that unit.

You cannot have two identifiers that have the same name, which is where these unit name spaces come in again. If you have two variables named bar, one in the foo unit and the other in the re unit then you could reference them as foo.bar and re.bar respectively.

Granted if you make a single unit that has unit global variables and then use that unit from every other unit in your project then you come pretty close to having a global variable, but not quite. If you make use of any built in or 3rd party libraries then your variable is still not globally available inside those units.

No comments: