Inline list of object initialisation

You define a list variable and initialize it at the same time as shown in the following example

List<String> myStrings = new List<String> { 'one', 'two' };

How would I do this for a static list of object within my PostInstallScript? I know it is not necessary, however I feel my current code (below) is not very optimal and I am making multiple calls to the list Of Codes collection.

List<Special_Codes__c> listOfCodes = new List<Special_Codes__c>();
listOfCodes.add(new Special_Codes__c(Name='A1', Meaning__c='Special Customer', Type__c='Customer Code'));
listOfCodes.add(new Special_Codes__c(Name='A2', Meaning__c='Bad Customer', Type__c='Customer Code'));
listOfCodes.add(new Special_Codes__c(Name='DF', Meaning__c='Poor Customer', Type__c='Customer Code'));
listOfCodes.add(new Special_Codes__c(Name='A3', Meaning__c='Rich Customer', Type__c='Customer Code'));
listOfCodes.add(new Special_Codes__c(Name='Z1', Meaning__c='Household Customer', Type__c='Customer Code'));
listOfCodes.add(new Special_Codes__c(Name='Z3', Meaning__c='Average Customer', Type__c='Customer Code'));
listOfCodes.add(new Special_Codes__c(Name='ZX', Meaning__c='Private Business', Type__c='Customer Code'));
listOfCodes.add(new Special_Codes__c(Name='AB', Meaning__c='Homebased Business', Type__c='Customer Code'));

Answer

This cuts down on noise in the code and so is worth doing whether or not there is any performance benefit:

List<Special_Codes__c> listOfCodes = new List<Special_Codes__c>{
        new Special_Codes__c(Name='A1', Meaning__c='Special', Type__c='Customer Code'),
        new Special_Codes__c(Name='A2', Meaning__c='Bad', Type__c='Customer Code'),
        ...
        };

Also personally I prefer the (largely interchangeable with the list syntax but shorter) array syntax:

Special_Codes__c[] listOfCodes = new Special_Codes__c[] {
        new Special_Codes__c(Name='A1', Meaning__c='Special', Type__c='Customer Code'),
        new Special_Codes__c(Name='A2', Meaning__c='Bad', Type__c='Customer Code'),
        ...
        };

Attribution
Source : Link , Question Author : developer__c , Answer Author : Keith C

Leave a Comment