-1

I am failing to get my head around the C# get/set properties. I have read discussion about this topic in the internet, but still cant understand the real benefit of it.

Hope that someone could point me to the right direction by the following example, thanks.

Example 1: Using get and set properties

using System;
class Person
{
private string myName ="N/A";
private int myAge = 0;

// Declare a Name property of type string:
public string Name
{
    get 
    {
       return myName; 
    }
    set 
    {
       myName = value; 
    }
}

// Declare an Age property of type int:
public int Age
{
    get 
    { 
       return myAge; 
    }
    set 
    { 
       myAge = value; 
    }
}

public override string ToString()
{
    return "Name = " + Name + ", Age = " + Age;
}

public static void Main()
{
    Console.WriteLine("Simple Properties");

    // Create a new Person object:
    Person person = new Person();

    // Print out the name and the age associated with the person:
    Console.WriteLine("Person details - {0}", person);

    // Set some values on the person object:
    person.Name = "Joe";
    person.Age = 99;
    Console.WriteLine("Person details - {0}", person);

    // Increment the Age property:
    person.Age += 1;
    Console.WriteLine("Person details - {0}", person);
}
}

Example 2: Using normal method

  using System;
  class Person
  {
  private string myName ="N/A";
  private int myAge = 0;

// Declare a Name property of type string:
public string GetName() 
{
   return myName; 
}

public SetName(string value) 
{
   myName = value;
}

// Declare an Age property of type int:
public int GetAge() 
{ 
   return myAge; 
}

public setAge(int value) 
{ 
   myAge = value; 
}

public override string ToString()
{
    return "Name = " + Name + ", Age = " + Age;
}

public static void Main()
{
    Console.WriteLine("Simple Properties");

    // Create a new Person object:
    Person person = new Person();

    // Set some values on the person object:
    person.SetName("Joe");
    person.SetAge = 99;
    Console.WriteLine("Person details - {0}", person);

    // Increment the Age property:
    person.SetAge(person.SetAge + 1);
    Console.WriteLine("Person details - {0}", person);
 }
 }

So, my question is, is there any difference if I use the method 2 rather than method 1. Does method 1 provides extra benefit? Thanks.

Marko Topolnik
  • 195,646
  • 29
  • 319
  • 436
Alvin
  • 515
  • 6
  • 11
  • 1
    There is a difference: the former needs one method(property) the latter needs two. The former is just easier to maintain and also more redable since it's clear that it's the same property. – Tim Schmelter Mar 03 '14 at 14:00
  • I think this is duplicate question: http://stackoverflow.com/questions/2252573/why-use-getters-and-setters – Oscar Bralo Mar 03 '14 at 14:02
  • The link you provided didnt really solve my question because both examples above achieved the encapsulation purpose. My question is why should we still use get/set rather than normal method if everything is the same. From the other's opinion, it seems that get/set method is more a syntax issue, which makes the program more redable and easy to maintain. – Alvin Mar 03 '14 at 14:18
  • @user3239593: if you came from Java world, then you must carefully rethink your approach. "why should we still use get/set rather than normal method" - you see, the point is that GetName/SetName is **not** a normal method. In terms of ObjectOrientedDesign, if you want to expose a thing that "acts like an attribute of an object" and not like "an operation/action" - why are you forcing yourself to convert an attribute to pair of operations? Plain fields **are the most natural** representation of an attribute. However, traditional fields lack the ability to 'react' upon being used. – quetzalcoatl Mar 03 '14 at 14:26
  • And this is a severe limitation. That's why the global community agreed that traditional _fields_ should be private and that we should use some other ways of accessing the data that allows the target object to react. In Java, that's GetName/SetName because there's **no other option**. In Ruby, there's just methods: `name()` and `name()=` and language/compiler knows how to use them, and you use them like an attribute: `obj.name="mom"`. But it's tricky and **implicit**. .Net's properties take best of it: definition is explicit, and they are easy to use, and they are used similar to fields. – quetzalcoatl Mar 03 '14 at 14:29

2 Answers2

4

Properties are indeed some syntax sugar for getter and setter methods. Bbut the difference is not cosmetic.

The difference lies in Type information and coherence of naming.

With Get/Set methods, it's easy to accidentally make a typo in the name of one of them. This may cause some pairing mechanisms to fail. With properties, there's no change: the getter is always get_PROPNAME and setter is always set_PROPNAME.

There's a similar problem with types of return value and accepted parameters: the properties guarantee those are same.

Also, there's Reflection through which you may inspect the object at runtime. With Get/Set methods you must devise your own ways of guessing how Get/Set should be paired. It may seem easy, but with inheritance and overloads it may get hairy. It gets even more complicated in terms of finding, for example, what Attributes are applied to which one (for example, should [NonPersistent] applied at GetName apply to SetName that does not have such attribute?). With properties, there is no such problem.

In other words: Properties are what they are named for: they define a property. Readable, writeable, readonly, writeonly, partially public, virtual, etc - but a Property.

Methods, even named nicely as Get/Set - are separate methods. If they are to be used as a 'property' - it's simply harder to keep them in sync properly.

Proof:

Even your code example, simple at it is, got them mispaired, look:

public int GetAge()       // <- different character casing
 ...
public setAge(int value)  // <- different character casing

Edit: three more cents

As the language and platform support a notion of Properties, there are many things that actually rely on Properties being used properly.

Many standard mechanisms inspect the classes and look explicitely for Properties:

  • UI frameworks and their data bindings (WPF! WinForms! ..)
  • Serialization and ORM frameworks (EF! NH! XPO! ..)
  • classic and widely used change-notification mechanisms are bound to properties by design (INotifyPropertyChanged!)

and so on. If you resign from using Properties, you automatically lose it. I personally cannot imagine writing WinForms or WPF app without data-bindings, but YMMV of course :)

quetzalcoatl
  • 32,194
  • 8
  • 68
  • 107
  • 1
    Great answer! I would also add that using properties allows you to document the getter and and setter as a single entity, instead of writing it in two separate sections of the documentation with links to each other. – Idan Arye Mar 03 '14 at 14:23
0

It makes your code shorter, and easier to read. Even better would be to take advantage of the automatic getters and setters that were introduced in c# 3.

public string FirstName {get; set;}

public string FirstName {get; private set;}

public string FirstName {get; protected set;}

You still have the advantage of private setting, but your code is much shorter and more readable. Your Person class could then be rewritten to have the exact same functionality, but significantly shorter:

public class Person
{
    public string Name { get; private set; }
    public int Age { get; private set; }

    public Person(string name, int age)
    {
        Name = name;
        Age = age;
    }

    public override string ToString()
    {
        return string.Format("Name = {0}, Age = {1}", Name, Age);
    }
}
Jedediah
  • 1,916
  • 16
  • 32