简体   繁体   中英

What is the difference between these two C# console.write syntaxes?

I'm relatively new to C#. In going through some online practice exercises for C# console apps, I came across something I found to be interesting. If I were asked to output a variable to the screen, I would simply use:

 Console.Write(variable);

but when I look this up in various tutorials they say it should be written like this:

  Console.Write("{0}", variable);

why is this different way listed as opposed to the way I would naturally do it?

Since you only have one variable, there's no difference. The second version is for writing formatted strings. It works the same way as String.Format Eg:

Console.Write("The {0} Saturday this month is {1:dd MM yyyy}", "First", new DateTime(2015,6,13));

console.write("{0}", variable); is an overload of the Console.WriteLine method which displays a formatted result string to the console. Nevertheless for your case the outputs will be exactly the same.

References:

A composite format string contains some combination of actual text and format items that will be substituted with values of corresponding placeholders at run-time. For example:

string name = "Ahmer";

int age = 22;

Console.WriteLine(string.Format("{0} is {1} yrs old. {0} is old.", name, age))

Output:

Ahmer is 22 yrs old.

A format item is indicated by a 0-based index within a pair of braces. Notice that you can have multiple format items that refer to the same placeholder. You can also include the format items in any order. At run-time, each format item is evaluated and the appropriate value is substituted. For example:

Console.WriteLine(string.Format("Age: {1}, Name: {0}.  {1} {1} {1}..", name, age));

Age:22,Name: Ahmer. 22 22 22

As said the output would be the same but String.Format (which quals the overload of Console.Write with two parameters) makes code much easier to read/write/maintain.

But if you are interested in the performance take a look here... String output: format or concat in C#?

edit: removed old values because testing was not reliable... updated with better results

these lines have been executed 1000000 times, without any console output. From the performance kind of view formatting takes some time when using random values (not that you will normally realise it)

  • 513 ms - string.Format("{0} {1}", p.FirstName, p.LastName);
  • 393 ms - (p.FirstName + " " + p.LastName);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM