1

I am curious to know the difference between these two List statements one using curly braces and other one parenthesis. Any thoughts please. Thanks.

List<BPSyncConfiguration__c> bps = new List<BPSyncConfiguration__c> {};
List<BPSyncConfiguration__c> bpss = new List<BPSyncConfiguration__c> ();
2
  • 1
    More examples and comments - Collection initialization.
    – Keith C
    Commented Jan 2, 2016 at 10:26
  • Thanks @KeithC. I have used your blog as a bible for most of my coding. Definitely will take a look.
    – Bforce
    Commented Jan 2, 2016 at 11:46

2 Answers 2

2
List<BPSyncConfiguration__c> bps = new List<BPSyncConfiguration__c> {
                                      new BPSyncConfiguration__c(Name = 'Test Name 1'),
                                      new BPSyncConfiguration__c(Name = 'Test Name 2')
}; // We can pass multiple records here
List<BPSyncConfiguration__c> bpss = new List<BPSyncConfiguration__c> (bps); // We can pass another list here

We can use add method for both the above list i.e. bps, bpss

BPSyncConfiguration__c bp1 = new BPSyncConfiguration__c(F_SalesOrg__c = 'test'); 
bps.add(bp1);
BPSyncConfiguration__c bp2 = new BPSyncConfiguration__c(F_SalesOrg__c = 'test'); 
bpss.add(bp2);
2
  • Is this valid to add records to the second format of list above? For example, BPSyncConfiguration__c bp1 = new BPSyncConfiguration__c(F_SalesOrg__c = 'test'); bpss.add(bp1);
    – Bforce
    Commented Jan 2, 2016 at 6:11
  • Yes, We can use add BPSyncConfiguration__c bp1 = new BPSyncConfiguration__c(F_SalesOrg__c = 'test'); bpss.add(bp1); and for first list as wll
    – Ratan Paul
    Commented Jan 2, 2016 at 6:14
1

I assume you're interested in C# so:

By declaring your variable like in the first example, you're leveraging the "object initializer" syntax. By doing this, the compiler invokes the List's Add method for every object in between the curly braces (if any), AFTER the List's pulic, parameter-less constructor has been executed. Furthermore you can also do this with any type of object, not just for collections. I.e. you could initialize an object like this:

Person john = new Person { Name = "John" };

With the second type of initialization, you are constructing your object by directly invoking its public, parameter-less constructor and nothing more.

In both cases, it is totally possible (and legal) to subsequently invoke Add() or any other method/property of the object.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .