In this code:
Console.WriteLine("Hello {0}", name);
How is this {0} called?
I'm starting in C# and I've seen some codes with this.
I kind of know how it works, but why should I use ("Hello {0}", name)
instead of ("Hello " + name)
?
In this code:
Console.WriteLine("Hello {0}", name);
How is this {0} called?
I'm starting in C# and I've seen some codes with this.
I kind of know how it works, but why should I use ("Hello {0}", name)
instead of ("Hello " + name)
?
So, the following is the Format args pattern which is similar to String.Format
Console.WriteLine("Hello {0}", name)
// or
Console.WriteLine(string.Format("Hello {0}", name));
if you look at the source code to this overload of WriteLine
, you will find actually it calls String.Format
WriteLine(string.Format(FormatProvider, format, arg0));
You could however use
Console.WriteLine("Hello " + name)
There is no real difference 1, however you miss out on all the extra format abilities of String.Format
(though in your case you are not using any of them anyway)
You could also use the more modern string interpolation
Console.WriteLine($"Hello {name}")
As to what you want to use, depends on what you need to do, and what you are comfortable with. All have their advantages and disadvantages
Further reading
$ - string interpolation (C# reference)
1 As noted by @Zero String.Format
actually does a lot internally, so it's slower.
It is called string interpolation. Below is a useful reference
https://dotnetcoretutorials.com/2020/02/06/performance-of-string-concatenation-in-c/