Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to declare static variables in Delphi 2009?

I googled,I binged,I already have seen the other "duplicates" here,but none of them work in Delphi 2009 updated up to update 4.

Like in C#,I want to make a static variable in on line or as short as possible.In the end it works like a global variable,but its sorted.

What's the shortest way to do this in delphi 2009?

EDIT

I followed some of your answers,but it doesn't work.

type:

type
TmyClass = class(TObject)
  var staticVar:integer;
end;

code:

procedure TForm1.Button1Click(Sender: TObject);
var a:integer;
begin
  TMyClass.staticVar := 5; // Line 31
  a := TMyClass.staticVar; // Line 32
  MessageBox(0,IntToStr(a),'',0);
end;

I get the following errors:

[DCC Error] Unit1.pas(31): E2096 Method identifier expected 

[DCC Error] Unit1.pas(32): E2096 Method identifier expected
like image 716
Ivan Prodanov Avatar asked Jul 08 '09 06:07

Ivan Prodanov


People also ask

How do you declare static variables?

C++ Programming Class variables also known as static variables are declared with the static keyword in a class, but outside a method, constructor or a block. There would only be one copy of each class variable per class, regardless of how many objects are created from it.

Where are static variables saved?

When the program (executable or library) is loaded into memory, static variables are stored in the data segment of the program's address space (if initialized), or the BSS segment (if uninitialized), and are stored in corresponding sections of object files prior to loading.

What is a swift static variable?

Static variables are those variables whose values are shared among all the instance or object of a class. When we define any variable as static, it gets attached to a class rather than an object. The memory for the static variable will be allocation during the class loading time.

What is static variable in Android Studio?

The static variable can be used to refer to the common property of all objects (which is not unique for each object), for example, the company name of employees, college name of students, etc. The static variable gets memory only once in the class area at the time of class loading.


1 Answers

type
  TMyClass = class(TObject)
  private
    class var FX: Integer;
  public
    class property X: Integer read FX write FX;
  end;

or shorter if you don't use a property

type
  TMyClass = class(TObject)
  public
    class var X: Integer;
  end;

edit: Note the class in class var. You forgot that part.

like image 57
Lars Truijens Avatar answered Sep 28 '22 06:09

Lars Truijens