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

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

    It refers to the index number of the parameter. For example, if you want to print multiple variables you can do this:

    Console.WriteLine("Person details - {0} {1}", person1, person2)
    
    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2020-12-20 07:55

    It refers to the index of the given variable (first variable, second variable, etc.), whose contents you want to write. You have just one variable (person), that's why you can only set the first index (0).

    In Console.WriteLine("Person details - {0}", person); the {0} means: write the contents of the first variable right where {0} is.

    0 讨论(0)
  • 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[].

    0 讨论(0)
  • 2020-12-20 08:03

    the best way to learn about this stuff is the examples-part of this site:

    Console.WriteLine Method (String, Object)

    0 讨论(0)
提交回复
热议问题