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

前端 未结 5 1240
夕颜
夕颜 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:52

    In Write/WriteLine calls the first parameter is the format string. Format specifiers are enclosed in curly braces. Each specifier consists of a numeric reference to the parameter that needs to be "plugged into" the format string as the replacement of the said specifier, and optional formatting instructions for the corresponding data item.

    Console.WriteLine(
        "You collected {0} items of the {1} items available.", // Format string
        itemsCollected,                                        // Will replace {0}
        itemsTotal                                             // Will replace {1}
    );
    

    This is similar to printf in C/C++, where %... specify the formatting for the corresponding item from the list of arguments. One major difference is that the printf family of functions requires that parameters and their format specifiers were listed in the same order.

提交回复
热议问题