+ Start a Discussion
PlatFormCloudPlatFormCloud 

Getter and Setter in Apex

Hi experts,
Very basic question and find difficult to understand. And please let me know, when to use what?

What is the difference between these 2 coding structures:
1.  public String name {
         get { return name;}
        set { name = value;}

2. public String name{get;set;}
CloudGeekCloudGeek
Hello PlatFormCloud,

Take a look at this link:

http://www.forcetree.com/2009/07/getter-and-setter-methods-what-are-they.html

Hope that helps!

Note: Mark it as solution if this helps .
Mayank Pant 11Mayank Pant 11

Hi,
Get (getter) method is used to pass value from controller to VF page while set (setter) is used to set the value back to controller variable. 

Above two methods are same and will return same results. Only their style of coding is different.

But if you modify getter setter method with below code then it will change the result.

For example name is 'John'

 public String name {
         get { return name + 'Get Value';}
        set { name = value +' Set Value';}
In above code getter result will be "John Get Value' and Setter result will be "John Set Value" 

Please mark it Solved if it has resolved your query.

Thanks,
Mayank

PlatFormCloudPlatFormCloud
Is there any order of firing the getter and setter method? Is 'setter' method triggers first than 'getter' method?

Thanks!
Jason PappJason Papp
Those two code examples are functionally equivalent. The following code creates a property with a basic getter and setter:
Public String name { get; set; }
The other forms come into play when you want to format or validate data in some way. For example, if you want names to have the first letter uppercase and the rest lowercase:
Public String name {
    get { return name; }
    set { name = value.toLowerCase().capitalize(); }
}
Is there any order of firing the getter and setter method? Is 'setter' method triggers first than 'getter' method?
No, only one or the other is called at a time. Any time you access the property, get is called. Any time you store a value, set is called.