Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

initializing objects in delphi

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?

like image 540
vesal Avatar asked Aug 29 '26 22:08

vesal


1 Answers

As pointed out by others there is no object initializer syntax like there is in C#.

There are a few alternatives that come close.

  1. ja-mesa already pointed out the 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.
  2. 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);
    
  3. 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.

  4. Constant records also come very close.

    const
      MyRecord: TMyRecord =
      (
        FirstName : 'Craig';
        LastName : 'Playstead';
      );
    

    The obvious drawback being that it is a constant

  5. 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;
like image 168
Kenneth Cochran Avatar answered Sep 01 '26 15:09

Kenneth Cochran



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!