This program demonstrates the evolution of property implementation in C#, from traditional getter/setter methods to modern .NET properties.
static void Main(string[] args)
{
Person person = new Person();
person.Name = "abc"; // Calls the Name property's SET accessor
person.Address = "Kolkata"; // Calls the Address property's SET accessor
string details = person.GetDetails();
Console.WriteLine(details);
Console.ReadLine();
}
What happens:
Person
objectName
property to "abc" (internally calls the setter)Address
property to "Kolkata"GetDetails()
method to get formatted output#region Private Members
private int _No;
private string _Name;
private string _Address;
#endregion
These are backing fields - private variables that store the actual data. The underscore prefix (_
) is a common naming convention for private fields.
public string Name
{
get { return "Mr / Mrs " + _Name; } // Getter: formats the name
set { _Name = value; } // Setter: stores the value
}
public string Address
{
get { return _Address; } // Simple getter
set { _Address = value; } // Simple setter
}
Key Points:
string name = person.Name
)person.Name = "John"
)Name
property adds "Mr / Mrs " prefix when returning the value