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

北慕城南 提交于 2019-12-06 14:47:08

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

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)

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.

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.

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

Console.WriteLine Method (String, Object)

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!