10

I've got a simple component class with boolean property:

  TmyClass = class(TComponent)
    private
      fSomeProperty: boolean;
    published
      property SomeProperty: boolean 
                  read fSomeProperty 
                  write fSomeProperty
                  default true;

  end;

I put it on my form, set it to true (SomeProperty is set to false, why?), but when i'm trying to access SomeProperty from run-time it's giving me false. Why is that so?

JustMe
  • 2,329
  • 3
  • 23
  • 43

2 Answers2

17

Thats because the default specifier don't actually assign the value to the property, it just says to the streaming system which value is the default (and thus doesn't need to be saved). You still have to initialize the prop/field in the constructor to the desired default value. This is documented in the help btw, read the "Storage Specifiers" section

ain
  • 22,394
  • 3
  • 54
  • 74
  • +1; I haven't found anything useful on `default` specifier except that in Object Inspector when you change the value of some property from the `default` one, it's highlighted by the bold font; if you change it back to `default` the bold style is removed. –  Aug 04 '11 at 16:15
  • 2
    As @ain said, read the Storage Specifiers section of the help or DocWiki. This says: `Note: Property values are not automatically initialized to the default value. That is, the default directive controls only when property values are saved to the form file, but not the initial value of the property on a newly created instance.` – Rudy Velthuis Aug 04 '11 at 16:22
  • 3
    So to fix it, add the constructor code `FSomeProperty := true` – Warren P Aug 04 '11 at 18:48
6

You should also set the property to True in the constructor - otherwise it is an error:

constructor TMyClass.Create(AOwner: TComponent);
begin
  inherited;
  FSomeProperty:= True;
  ...
end;

Default values determine what will be stored in *.DFM file. If you set FSomeProperty to True at design time, and default value for FSomeProperty is True, then FSomeProperty will not be stored in *.DFM.

If you don't initialize FSomeProperty to True in the constructor you get an error you described - FSomeProperty appears False at runtime, though it was set True at design time.

kludg
  • 27,213
  • 5
  • 67
  • 118