-1

Is there a more proficient way to add spaces to the output?

//define variables
string myName;
int myAge;

//input
Console.Write("Enter Name:");
myName = (Console.ReadLine());
Console.Write("Enter Age:");
myAge = int.Parse(Console.ReadLine());

//output
Console.Write("Hello" + " " + myName + " " + "Your age is" + " " + myAge);
Console.ReadKey();
Rob
  • 26,989
  • 16
  • 82
  • 98
Shmaves
  • 1
  • 2
  • 2

2 Answers2

4

You could use String.Join

Example:

String.Join(" ", "Hello", myName, "Your age is", myAge);

Note: Since you asked about adding white spaces this would be the way, however I highly recommend you to use string interpolation (c# 6) or string formatting via String.Format

J. Steen
  • 15,470
  • 15
  • 56
  • 63
Darjan Bogdan
  • 3,780
  • 1
  • 22
  • 31
  • 2
    @abelenky you are absolutely wrong, String.Join takes params string[] values (in one of four overloads). Please read about params keyword on the https://msdn.microsoft.com/en-us/library/w5zay9db.aspx – Darjan Bogdan Mar 10 '17 at 08:19
  • 2
    Apparently not absolutely wrong, just old-school. the `params` wasn't added until .Net 4.0. From versions 3.5 and earlier, it was `(String, String[])`, only. – abelenky Mar 10 '17 at 08:24
0

Can you use C# 6? Then use string interpolation. Is much more elegant.

Example:

"Hello" + " " + myName + " " + "Your age is" + " " + myAge

becomes

$"Hello {myName} Your age is {myAge}"

Slepz
  • 460
  • 3
  • 18
Alex
  • 3,689
  • 1
  • 21
  • 32
  • I could use c#6 but as I am taking a Tafe course in Programming basics c# is what I have to use for now. I will read into string interpolation though. Thanks. – Shmaves Mar 10 '17 at 08:33
  • @Shmaves Well, string interpolation is just syntax sugar for `string.Format()` so it will be good for you to understand where it came for. Keep up the good work. – Alex Mar 10 '17 at 08:39