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.