why we use {get; set;} syntax in wrapper class or in controller class

public class Wrapper
{

   public String fname{get; set;} //why we use get; set; syntax here
   public String lname{get; set;}
   public String uname{get; set;}
}

also here

public class Controller{
    public List<Wrapper> WrapperList {get;set;}
    public string sourceURL {get; set;}
}

how these get; set; methods work.

Answer

{get; set;} can appear in any apex class, next to any class variable (thus making it a ‘property’).

The <access identifier> <type> <variable name> {get; set;} pattern is simply a shortcut. Using that syntax tells Salesforce to automatically generate the getter and setter methods for that class variable.

Of course, you don’t need to use that syntax, but then again, we also don’t need to use automobiles to travel long distances (walking will do the job just fine, albeit more slowly).

If you don’t feel like using this:

public class MyClass{
    public String myVariable {get; set;}
}

You can always do it the long way

public class MyClass{
    public String myVariable;

    public void setMyVariable(String input){
        myVariable = input;
    }

    public String getMyVariable(){
        return myVariable;
    }
}

With having public class variables though, you don’t really need to specify setters and getters. You can just get/set the value directly.

However, for reasons that are beyond the scope of this answer (and this site), directly accessing class variables is poor practice in object-oriented programming (Apex being an object-oriented programming language).

Attribution
Source : Link , Question Author : Saroj Dhabale , Answer Author : Derek F

Leave a Comment