CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 5 of 5
  1. #1
    Join Date
    Dec 2006
    Posts
    7

    Question Getters and setters

    Hi,
    I am very new to c#.
    While i was trying to declare a variable variab as private and use the getters and setters to access it.

    I see the syntax like

    Code:
    namespace MyTest{
    class Person
    {
      private string vv {get;set;} // variable vv is private and I want to access it using the public member functions get and set
    }
    
    class myMain{
    
    static void Main(string[] args)
    {
        Person obj = new Person();
        obj.vv = "NewText"; // Compilation error
    }
    }
    }
    But when i compile the code it is giving compilation error. Help me understanding this.

  2. #2
    Arjay's Avatar
    Arjay is offline Moderator / EX MS MVP Power Poster
    Join Date
    Aug 2004
    Posts
    13,490

    Re: Getters and setters

    The compiler error is that you are trying to access a private class member. Private class members can only be accessed from inside the class where they are declared.

    Besides that it is important to understand the difference between a class field, property and auto-property in c#.

    A field in C# is declared as:
    Code:
    public class Person
    {
      public string Name;
    }
    The field is accessed as
    Code:
    var person = new Person();
    person.Name = "Fred"; // set the Name field to Fred
    var n = person.Name; // get the Name value (Fred)
    Fields are okay, but they have some disadvantages. First, they don't allow for encapsulation. In other words, if you make the field public, you can't control who sets it from who gets it. Next, you also can't have a field that is get only or set only. Finally, they don't allow for computing the value in the get or setting more than one field in the set.

    So C# introduced the property which is declared as the following. Non-auto-properties required a 'backing' field (e.g. _name) which store the value.
    Code:
    public class Person
    {
      public string Name
      {
         get { return _name; }
         set { _name = value; }
      }
      private string _name;
    }
    The property (like the field) is accessed as
    Code:
    var person = new Person();
    person.Name = "Fred"; // set the Name field to Fred
    var n = person.Name; // get the Name value (Fred)
    From outward appearances, there doesn't seem to be much difference between a field and a property, but there is some syntactical sugar going on with the property.
    What is going on when you declare a property like the above example, the compiler creates the following getter and setter method pairs beneath the covers:
    Code:
      public string Name_get()
      {
         return _name;
      }
      public string Name_set(string value)
      {
         _name = value;
      }
    So when you access the property by setting and getting the value, this is actually what is going on:
    Code:
    var person = new Person();
    person.Name = "Fred"; // set the Name field to Fred - internally the Name_set("Fred") method is called
    var n = person.Name; // get the Name  - internally the Name_get() method is called
    Therefore properties are nothing more than compiler generated getters and setters (when the compiler generates a developer convenience, it is often called "syntactical sugar").

    As mentioned, properties also allow for computing a value during the get as well as setting more than one property (or calling methods) inside the set:
    Code:
    public class Person
    {
      public string Name
      {
         get { return string.Format("Name accessed by the get: {0}", _name); }
         set { SetTheName(value); }
      }
    
      private void SetTheName(string value)
      {
         _name = string.Format("Value of name from SetTheName: {0}", value);
      }
      private string _name;
    }
    The property with multiple get/set operations is called the same way as any other property:
    Code:
    var person = new Person();
    person.Name = "Fred"; // sets the _name to "Value of name from SetTheName: Fred".
    var n = person.Name; // get the Name value as "Name accessed by the get: Value of name from SetTheName: Fred";
    In the contrived example above, the ability to perform different operations within the getters/setters of a property may not appear useful, but in practice it turns out to be extremely useful.

    This brings us to the discussion of what an auto-property is. The auto property requires no backing field - the compiler generates this for you.
    Auto-Properties are declared below. Notice how the get and set bodies are empty and a backing field isn't declared. This makes properties as convenient to declare as a field, but with the benefits of a property.
    Code:
    public class Person
    {
      public string Name { get; set; }
    }
    Another thing to mention is that the visibility of the get and set declarations can be controlled with the access level (public, protected, private). The outer property declaration is defined, but the inner getter setter can override the access. For example, below the get is public and the set is overridden to private (and must be set in the constructor). This works for regular properties or auto-properties.
    Code:
    public class Person
    {
      public string Name { get; private set; }
    }
    Lastly, unlike fields, properties can be declared with a get, set or both. The get:
    Code:
    public class Person
    {
      public string Name { get; } = "Fred"; // Note: C# 7.0 or .Net Core initialization syntax
    }
    The property can be accessed with get but trying to set the value results in a compile time error.
    Code:
    var person = new Person();
    person.Name = "Fred"; // Compiler error
    var n = person.Name; // returns "Fred"
    Now, the set only: (notice I'm using a backing property here)
    Code:
    public class Person
    {
      public string Name { set { _name = value; } };
    
      private string _name; // class methods can access this backing field
    }
    The property can be set, but using get results in a compile time error.
    Code:
    var person = new Person();
    person.Name = "Fred"; // Sets Fred
    var n = person.Name; // Compiler error
    Last edited by Arjay; February 16th, 2019 at 06:32 PM.

  3. #3
    Join Date
    Dec 2006
    Posts
    7

    Re: Getters and setters

    Thanks you explained so nicely.

  4. #4
    Join Date
    Feb 2017
    Posts
    677

    Re: Getters and setters

    Even though it's important to know how to use getters/setters it's also important to know when to use them. And the answer is simple, as seldom as possible, at least if you're aiming for object oriented (OO) design.

    It's because although getters/setters offer a higher degree of encapsulation than exposing the naked variable, you get even more encapsulation if you don't expose the variable at all. So the OO way is to ask objects to do things for you, not to shuffle data in and out of them.

    Unfortunately it has become some kind of routine measure among many programmers to first hide all variables by making them private only to immediately expose them again by way of public getters/setters. This is a bad habit, not proper OO.

  5. #5
    Arjay's Avatar
    Arjay is offline Moderator / EX MS MVP Power Poster
    Join Date
    Aug 2004
    Posts
    13,490

    Re: Getters and setters

    I agree in principle that that taking encapsulation to the furthest level would be to keep everything internal. However, if a system interacts with external components, the component interface will generally need to expose objects containing public properties. For example, in a system that uses a service layer, the service layer interface will contain methods that pass objects. Typically these objects (usually called DTOs or data transfer objects) expose public properties.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured