Search code examples
c#visual-studio

How to print values of multiple variables in one Console.WriteLine() statement?


I have three variables, firstName, middleName and lastName. I am reading the values of these three variables one by one as shown in the code below. I want to print the values of the three variables in one Console.WriteLine() statement. The output should be in the following way:

Let, firstName be: John; middleName be: Bradshaw; lastName be: Layfield

Output: John Bradshaw Layfield

Code:

Console.WriteLine("Enter First Name");
firstName = Console.ReadLine();
Console.WriteLine("\n");

Console.WriteLine("Enter Middle Name");
middleName = Console.ReadLine();
Console.WriteLine("\n");

enter code hereConsole.WriteLine("Enter Last Name");
lastName = Console.ReadLine();
Console.WriteLine("\n");

Solution

  • You should use string.Format to format your string with all 3 variables:

    Console.WriteLine(string.Format("{0} {1} {2}", firstName, middleName, lastName));
    

    You should use String Interpolation as of C# 6.0 to format your string with all 3 variables:

    Console.WriteLine($"{firstName} {middleName} {lastName}");