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

前端 未结 5 1237
夕颜
夕颜 2020-12-20 07:20

Given the code :

// person.cs
using System;

// #if false

class Person
{
    private string myName = \"N/A\";
    private int myAge = 0;

    // Declare a          


        
5条回答
  •  星月不相逢
    2020-12-20 07:57

    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[].

提交回复
热议问题