public class Car
{
public string Make { get; set; }
public string Model {get; set;}
public string Car(string make, string model)
{
Make = make;
Model = model;
}
public override string ToString()
{
return string.Format("{0}:{1}", Make, Model);
}
}
class Program
{
static void Main(string[] args)
{
Console.WriteLine("What is the Make of the car: ");
string make = Console.ReadLine();
Console.WriteLine("What is the Model of the car: ");
string model = Console.ReadLine();
Car car = new Car(make, model);
Console.WriteLine("The Make of the car is: {0}\nAnd the Model of the car is: {1}", car.Make, car.Model);
Console.WriteLine("The car is {0}", car);
Console.ReadLine();
}
}
"It worked, but what I didn't understand is how 'Console.WriteLine("Your Car: {0}", car);' knew where to get the formatted string. Because 'public override string ToString()' doesn't have any type of identifier involved in it to show ownership of what its trying to accomplish."
If you feed any variable into a string.Format method (and Console.WriteLine does just that - it feeds your parameters into string.Format and prints the result to the console) then it does an implicit yourVariable.ToString() call in order to get something it can print - if the variable isn't a string already.
The ToString method above accesses the two properties of the current instance of the Car class (also known as
this
) and fetches the relevant data. It could be re-written as:
public override string ToString()
{
return string.Format("{0}:{1}", this.Make, this.Model);
}
But the "this." bit is implied in all non-static methods, so can be left out for readability. Normally, I only include it if there is a duplication of names between a method parameter and a property or field.
Does that make sense?