No Results
Search Tips:
- Please consider misspellings
- Try different search keywords
Newer Version Available
Assignment Statements
An assignment statement is any statement that places a value into
a variable, generally in one of the following two forms:
1[LValue] = [new_value_expression];
2[LValue] = [[inline_soql_query]];In the forms above, [LValue] stands for any expression that can be placed on the left side of
an assignment operator. These include:
- A simple variable. For example:
1Integer i = 1; 2Account a = new Account(); 3Account[] accts = [SELECT Id FROM Account]; - A de-referenced list element. For example:
1ints[0] = 1; 2accts[0].Name = 'Acme'; - An sObject field reference that the context user has permission
to edit. For example:
1Account a = new Account(Name = 'Acme', BillingCity = 'San Francisco'); 2 3// IDs cannot be set prior to an insert call 4// a.Id = '00300000003T2PGAA0'; 5 6// Instead, insert the record. The system automatically assigns it an ID. 7insert a; 8 9// Fields also must be writeable for the context user 10// a.CreatedDate = System.today(); This code is invalid because 11// createdDate is read-only! 12 13// Since the account a has been inserted, it is now possible to 14// create a new contact that is related to it 15Contact c = new Contact(LastName = 'Roth', Account = a); 16 17// Notice that you can write to the account name directly through the contact 18c.Account.Name = 'salesforce.com';
Assignment is always done by reference. For example:
1Account a = new Account();
2Account b;
3Account[] c = new Account[]{};
4a.Name = 'Acme';
5b = a;
6c.add(a);
7
8// These asserts should now be true. You can reference the data
9// originally allocated to account a through account b and account list c.
10System.assertEquals(b.Name, 'Acme');
11System.assertEquals(c[0].Name, 'Acme');Similarly, two lists can point at the same value in memory. For
example:
1Account[] a = new Account[]{new Account()};
2Account[] b = a;
3a[0].Name = 'Acme';
4System.assert(b[0].Name == 'Acme');In addition to =, other valid assignment operators include +=, *=, /=, |=, &=, ++, and --. See Understanding Expression Operators.