I am VERY new to C# programming with a light backround in C++ and HTML, so I am pretty much starting from scratch. I was looking though the msdn tutorials, the properties tutorial specfically, and there is only one part so far I do not understand. There is a part in the code goes like this:
// person.cs
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);
}
}
and the program’s output is this:
Simple Properties
Person details - Name = N/A, Age = 0
Person details - Name = Joe, Age = 99
Person details - Name = Joe, Age = 100
Now I understand that {0} is effectivly a placeholder that references a part of the code, in this case it is “person”, but I do not understand how this part:
public override string ToString()
{
return "Name = " + Name + ", Age = " + Age;
}
is listed under “person”. I don’t see the connection like I do with “name” and “age”. Could someone highlight the part of the code that makes the connection and possibly explain it as well if it is not to much to ask? Thank you very much in advance.
You are using string formatting. The
WriteLinehas an overload where the first parameter is a format string, so you are doing the same thing as:The
Formatmethod takes the value parameters and turns them into strings, then inserts them into the format string. The standard method for turning anything into a string is calling theToStringmethod, which every objects has. If you want to specify what something looks like when it is turned into a string, you override theToStringmethod.So, in the end the code is doing the same as: