What does {0} stands for in Console.WriteLine?

JAN picture JAN · Oct 23, 2013 · Viewed 24.5k times · Source

Given the code :

// person.cs
using System;

// #if false

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);
    }
}

// #endif

The output of the code is :

Simple Properties
Person details - Name = N/A, Age = 0
Person details - Name = Joe, Age = 99
Person details - Name = Joe, Age = 100

What does the {0} in Console.WriteLine("Person details - {0}", person); stands for ? How come it's replaced by Name..... ?

When I put {1} instead of {0} I get an exception ...

Answer

111WARLOCK111 picture 111WARLOCK111 · Oct 23, 2013

As you can see, There's a code on your person object that returns a string, Console checks for If a type of string with name of ToString exists on your object class or not, If exists then It returns your string:

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

And {0} Is a formatted message, When you define It to {0} It means printing/formatting the zero Index object that you Inserted Into params arguments of your function. It's a zero based number that gets the index of object you want, Here's an example:

Console.WriteLine("{0} Is great, {1} Do you think of It? {2} Think {0} Is great!", "C#", "What", "I");

// C# Is great, What do you think of It? I think C# Is great!

When you say {0} It gets C# or the [0] of your object[].