Confusion in a really a basic question: I have seen in many books, they use use Console.WriteLine as:
int i = 12;
Console.WriteLine("MyVariable value is {0}", i);
Instead of
int i = 12;
Console.WriteLine("MyVariable value is" + i);
Is there any difference between them?
in your example, practically not. However, the first case can easily be extended to do
Console.WriteLine("MyVariable value is {0} and myothervar is {1}", i, j);
which could be a little cumbersom with the second approach.
Check out the answer in this thread. In a simple case it doesn't really matter, but there are performance considerations if you are doing this in a large loop or something.
Maybe this will help someone in the future. There is now a 3rd method(Interpolation) and it is the cleanest of them all! They are all just different ways of writing the same thing.
int i = 12;
// Interpolation Method- Req. C# 6 or later [Cleanest]
Console.WriteLine($"MyVariable value is {i}");
// Concatenation Method (from VB days)
Console.WriteLine("MyVariable value is " + i);
// Format Method (from C days)
Console.WriteLine("MyVariable value is {0}", i);
I believe you see the string concatenation in books for beginner because it is simple. String formatting needs to be explained before it can be used in such simple example. String concatenation is much simple and may already have been taught at that point in the book (even if not, it is simple enough to learn by example).
I can see how C programmers might be confused by the format syntax when encountering it for the first time. When attempting to extend it to two variables they might think it needs to be written as so:
int numA = 3;
int numB = 5;
Console.WriteLine("numA is {0} and numB is {0}", numA, numB);
Thinking it would be similar to C's printf
where {0}
is equivilant to %d
:
printf("numA is %d and numB is %d", numA, numB);
They would of course be surprised to have varA
be printed twice. Or they may be frustrated of not knowing the equivalent of %s
when trying to Console.WriteLine
a string. String concatenation, on the other hand, has fewer pitfalls and can be more easily extended by beginners. Of course it is more cluttered but also more powerful, power that may be confusing in a book introducing someone to C# since string formatting syntax can grow quite complex:
Console.WriteLine("numA is {0,17:$00.00####}", numA);
The above example also illustrates the difference between concatenation and string formatting. They are different, but for simple usages like the one you made, it makes little difference.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With