Apex Controllers: What do the get; set; do?

Visualforce requires a "getter" and "setter" to reference a variable in the controller or extension. Without a getter or setter, even public or global variables cannot be referenced in Visualforce expressions.

"get;" is basically: public *datatype* getVarName() { return varName; }

"set;" is basically: public void setVarName(*datatype* value) { varName = value; }

There are subtle differences though. For example, the function doesn't actually exist; it's called implicitly.

You can make variables read-only by not including set;, and you can make them write-only by not including get;.

Inside Apex Code, you can also use these to control readability and writeability.

For example:

public static Integer counter {
    get { if(counter == null) counter = 0; counter++; return counter; }
    private set; }

This counter increases by 1 each time it's used, but can't be set outside of the class that contains it.

public class OtherClass {
   public void someMethod() {
       System.debug(FirstClass.counter);
       System.debug(FirstClass.counter);
       FirstClass.counter = 10; // Compiler error
   }
}

Without the compiler error, it would debug 0, then 1.


What you are seeing with {get;set;} is an example of automatic properties.

From the Apex Documentation on Automatic Properties.

Properties do not require additional code in their get or set accessor code blocks. Instead, you can leave get and set accessor code blocks empty to define an automatic property. Automatic properties allow you to write more compact code that is easier to debug and maintain. They can be declared as read-only, read-write, or write-only. The following example creates three automatic properties:

Here is the example from the docs

public class AutomaticProperty {
   public integer MyReadOnlyProp { get; }
   public double MyReadWriteProp { get; set; }
   public string MyWriteOnlyProp { set; }
}

You could just as easily do something like this instead, but using the automatic properties saves a lot of time and coding.

public class nonAutomaticProperty {
   public integer MyReadOnlyProp { 
        public get {return MyReadOnlyProp;} 
        private set;
   }
   public double MyReadWriteProp { 
        public get {return MyReadWriteProp;} 
        public set; 
   }
   public string MyWriteOnlyProp { 
        private get {return MyWriteOnlyProp;} 
        public set; 
   }
}

This was answered on SF dev forums: Reg: Get and set Methods

That post linked to a great aticle on the behavior of the default get/set methods: Getter and setter methods - What are they??