I was just wondering about why should I use property in a class instead of “normal” variables (class attributes?). What I mean is this:
TSampleClass = class
public
SomeInfo: integer;
end;
TPropertyClass = class
private
fSomeInfo: integer;
public
property SomeInfo: integer read fSomeInfo write fSomeInfo;
end;
What is the big difference? I know that I can define getter and setter methods for getting or saving the property respectively, but that is possible even without the variable being a “property”.
I tried searching for why to use it, but nothing useful came up, so I’m asking here.
Thank you
This is just a very simple example of a specific case, but still, it is a very common case.
If you have a visual control, you might need to repaint the control when you change a variable/property. For instance, let’s say your control has a
BackgroundColorvariable/property.The simplest way of adding such a variable/property is to let it be a public variable:
And in the
TMyControl.Paintprocedure, you paint the background using the value of theBackgroundColor. But this doesn’t do it. Because if you change theBackgroundColorvariable of an instance of the control, the control doesn’t repaint itself. Instead, the new background colour will not be used until the next time the control redraws itself for some other reason.So you have to do it like this:
where
and then the programmer using the control has to use
MyControl1.GetBackgroundColorto obtain the colour, and to useMyControl1.SetBackgroundColorto set it. That’s awkward.Using properties, you can have the best of both worlds. Indeed, if you do
then
MyControl1.BackgroundColorproperty, and