Sting formating and Concatenation
Hi all the bellow code will produce the same out put but I am not sure which is the best method to use in code comming from VB6 we only had the second option open to us. Non of the C# books give much info on this area just thought someone out there could give me a hand.
Code:
int age=28;
string name="Bombdrop";
Console.WriteLine("hello {0} you are {1} years old",name,age.ToString());
Console.WriteLine("hello " + name +" you are " + age.ToString() + " years old");
thanks in advance!!
:wave: :thumb: :wave:
Re: Sting formating and Concatenation
Try
Code:
int age=28;
string name="Bombdrop";
Console.WriteLine( new String.Format("hello {0} you are {1} years old",name,age.ToString()));
Re: Sting formating and Concatenation
Thanks for the reply John but why is that the best option?
Re: Sting formating and Concatenation
It probably does not make much difference which method you use, but the one below makes it easier to write the string without having to worry about opening/ closing quotes and sticking in plus signs all over the place.
Code:
Console.WriteLine("hello {0} you are {1} years old",name,age.ToString());
Re: Sting formating and Concatenation
Code:
Console.WriteLine("hello {0} you are {1} years old",name,age.ToString());
That's the most easily readable and probably a hair faster. I'd use that.
Dan
Re: Sting formating and Concatenation
I made a little program that tested the two methods and they came out nearly the same, to the millisecond. The {param} method was on average about eight ms faster at repeating the command 1000 times. Hardly a difference I'd consider.
Dan
Re: Sting formating and Concatenation
This one:
Code:
Console.WriteLine("hello {0} you are {1} years old",name,age.ToString());
Uses exactly the same semantics as String.Format(), so there is absolutely no benefit in nesting String.Format inside the writeline call. Its an uneccessary step.
It is better to use the above method rather than using a lot of "+" operators, mainly because its easier to read and also because the object code will be a tiny bit smaller and will a tiny bit faster. :D
Re: Sting formating and Concatenation
I agree with Wossname, but the English major in me would make the following addition:
Code:
Console.WriteLine("Hello {0}. You are {1} year{2} old.",
name, age.ToString(), age == 1 ? "" : "s");