6

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
5
  • "...but its sorted" - what is that supposed to mean? Commented Jul 8, 2009 at 6:23
  • And on which scope level do you want to declare your static variable? Function level? Class level? Unit level? Commented Jul 8, 2009 at 6:24
  • edn.embarcadero.com/article/34324 .This here is what I want.Look at the static methods example."TMyClass.X := 17" is what I want to use without the need to create an instance of the class.However,it doesn't work for me in delphi 2009.I get syntax errors Commented Jul 8, 2009 at 6:36
  • Maybe it would help if you showed what you did and what the error is. Commented Jul 8, 2009 at 6:48
  • If you're getting syntax errors, then it's because you did something wrong. Go back and look at the example again from the article you cited. It is correct. Commented Jul 8, 2009 at 6:57

1 Answer 1

18
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.

Sign up to request clarification or add additional context in comments.

3 Comments

I edited my question so you can see my code.I get error when uing your code.
You can also specify a default value for the property.
You could, but it won't do you any good unless it is in the published section and you also set the default value in the constructor and you use streaming and since it is a static/class property streaming is of no use. :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.