Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

when and why to use C# accessor methods [duplicate]

Tags:

c#

accessor

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;     
}
like image 570
shawn deutch Avatar asked Aug 09 '10 21:08

shawn deutch


2 Answers

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
}
like image 84
Robert Greiner Avatar answered Nov 14 '22 23:11

Robert Greiner


The reasoning behind Getters/Setters is to protect the class from being broken when a user alters a field in an invalid way, and they allow you to change the implementation of your class while leaving the publicly exposed properties unchanged.

Unless you need some kind of validation or lazy-loaded properties then you can usually just use auto properties.

public string Name { get; set; }
like image 40
Struan Avatar answered Nov 14 '22 23:11

Struan