as you know initializing object in c# is really handy and fast
StudentName student2 = new StudentName
{
FirstName = "Craig",
LastName = "Playstead",
};
and
List<MyObject>.Add(new MyObject{a=1,b=2})
is it possible to initializing objects in Delphi like this?
As pointed out by others there is no object initializer syntax like there is in C#.
There are a few alternatives that come close.
with construct, though it's best to avoid this construct. You can see my blog for a (mostly) unbiased review of the pros and cons of using with as well as similar constructs in other languages and some alternatives.Anonymous methods can be used for this though they're a little verbose and kind of ugly:
TMyObject.Create(procedure(var FirstName, LastName: string)
begin
FirstName := 'Craig';
LastName := 'Playstead';
end);
A fluent interface can come fairly close to approximating this:
TMyObject.Create
.FirstName('Craig')
.LastName('Playstead');
The downside being that writing a fluent interface is time consuming and only pays off if you plan on using this class a lot or are writing a public api.
Constant records also come very close.
const
MyRecord: TMyRecord =
(
FirstName : 'Craig';
LastName : 'Playstead';
);
The obvious drawback being that it is a constant
Another solution would be an overloaded constructor:
TMyObject.Create('Craig', 'Playstead');
Of course you could accomplish much the same thing by simply creating a temporary variable with a single character name.
var
o: TMyObject;
begin
o := TMyObject.Create;
o.FirstName := 'Craig';
o.LastName := 'Playstead';
Result := o;
end;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With