when and why to use C# accessor methods

shawn deutch picture shawn deutch · Aug 9, 2010 · Viewed 17.6k times · Source

Possible Duplicate:
C# - When to use properties instead of functions

I am trying to understand when and why to use "getters" and "setters"

would someone please provide some guidance.

What is the difference between the following constructs - please look in terms of accessor methods only.

//EXAMPLE 1: simple accessor method 
private static bool _isInitialEditMapPageLoad;
public static bool isInitialEditMapPageLoad
{
    get {return _isInitialEditMapPageLoad;}
    set {_isInitialEditMapPageLoad = value;}
}

//EXAMPLE 2: accessor method with a conditional test
private static bool _isInitialEditMapPageLoad;
public static bool isInitialEditMapPageLoad
{
    get 
    {
        if (currentSession[isAuthorizedUseder] == null)
            return false;
        else
            return _isInitialEditMapPageLoad;    
    }
    set {isInitialEditMapPageLoad = value;} 
}


//EXAMPLE 3: just a get accessor method - is this the same as EXAMPLE 4?
private static bool _isInitialEditMapPageLoad = false;
public static bool isInitialEditMapPageLoad
{
    get {return _isInitialEditMapPageLoad;}
}


//EXAMPLE 4: simple method
private static bool _isInitialEditMapPageLoad = false; 
public static bool isInitialEditMapPageLoad
{
  return _isInitialEditMapPageLoad;     
}

Answer

Robert Greiner picture Robert Greiner · Aug 9, 2010

Your getters/setters should be your public interface to your class.

As a rule of thumb, all of your members should be private except for what you want people to have access to outside of your class and you never want your private variables to be directly accessible outside if your class

Here's a simple example. say you had a class that you needed an age variable for. In this case, you could perform validation right there in the setter without your external classes needing to know that the value is validated.

class Person {
  int age = 0;

  public int Age {
    get { return age; }
    set { 
      //do validation
      if (valid) {
        age = value;
      }
      //Error conditions if you want them.
    }
  } 

  //More getters/setters
}