function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Sourav PSourav P 

Query in instance variable declaration

Can anyone plz explain the below red marked code syntax in simple words. i could't understand why the "new" keyword is inside the (), and what is the "{mail}" keyword? 
What is the proper syntax of theis code ?
User-added image

Rahul Kumar 767Rahul Kumar 767
Very Nice. Visit here Kalia Yojana  (
Hi Sourav,

Apex Email Message works on the built-in methods like SendEmail, SingleEmailMessage, sendEmailResult etc in Messaging class.
  • In your code 'Mail' is the variable which you gave to initialize the actual content of the singleEmailMessage in line 5 of your code. Having details like what is the subject, body,to Address.
In the code which is marked as red... consider second half (after = part of the code)

 Messaging.sendEmail( new Messaging.SingleEmailMessage[] { mail });
  • The method sendEmail(emails, allOrNothing)from messaging class is invoked with Messaging.sendEmail( ) and what sendEmail does is it sends the list of emails instantiated with either SingleEmailMessage or MassEmailMessage and returns a list of SendEmailResult objects.
  • Signature of sendEmail is
                  Public Messaging.SendEmailResult[] sendEmail(Messaging.Email[] emails, Boolean allOrNothing)
  • In your code as it is SingleEmailMessage you are Instantiating the singleEmailMessage list  like (new Messaging.SingleEmailMessage[ ]) with new keyword and passing the mail variable which has all the attributes in it like new Messaging.SingleEmailMessage[]{mail} and passing as parameter of sendEmail method
  • As it returns the list of type SendEmailResult you are using Messaging.SendEmailResult[] list (first part of the line) with variable name results and reading the value returned by sendEmail method into results variable.
Please refer these links for more on Messaging methods

Hope this helps! Please mark as best if it does.

ayu sharma devayu sharma dev
Hi Sourav,

If I tell you in simple words, it is a syntax for creating a new instance of an object in particular example its an instance of List and {mail} is the syntax of inserting a value inside the List when defining the List. The following example might help you.

This is a general code.
Lsit< Account > accountList = new List< Account >();
Account acct = new Account( Name = 'Test Name' );
accountList.add( acct );
Now the same code can be written as
Lsit< Account > accountList = new List< Account >{ new Account( Name = 'Test Name' ) } ;

So it is just a way to shorten the code and in some ways, it makes the code efficient also.

Hope you understand. If you still have some doubts you can without hesitation. 

Thanks and Regards
Ayush Sharma