Home > database >  Why I am not able to add different variables in Console.Write()
Why I am not able to add different variables in Console.Write()

Time:02-22

I have practiced following test and do not find a reason, why I cannot combine different kind of variables in Console.Write(), but in Console.WriteLine().


var firstName = "Bob";   //initialized as string
var inbox = 3;           //initialized as int
var degree = 34.4m;      //initialized as decimal

Console.Write("Hello, {0}", firstName);
Console.Write("! You have ");
Console.Write(inbox);
Console.Write(" in your inbox. The temperature is ");
Console.Write(degree);
Console.Write(" celsius.");

Console.WriteLine(" ");
Console.WriteLine("Hello, {0}! You have {1} in your inbox. The temperature is {2} celsius.", firstName, inbox, degree);

Why is the following solution not possible?


var firstName = "Bob";   //initialized as string
var inbox = 3;           //initialized as int
var degree = 34.4m;      //initialized as decimal

Console.Write("Hello, {0}", firstName);
Console.Write("! You have {1}", inbox);
Console.Write(" in your inbox. The temperature is {2}", degree);
Console.Write(" celsius.");

OR

Console.Write("Hello, {0}! You have {1} in your inbox. The temperature is {2} celsius.", firstName, inbox, degree);

CodePudding user response:

The solution is not possible because you should use string.Format for this purpose. In your example it should look like this

Console.Write(string.Format("Hello, {0}! You have {1} in your inbox. The temperature is {2} celsius.", firstName, inbox, degree));

Also remember that in each string format, the numeration of fields begin from zero, so instead of your code:

Console.Write("Hello, {0}", firstName);
Console.Write("! You have {1}", inbox);
Console.Write(" in your inbox. The temperature is {2}", degree);
Console.Write(" celsius.");

You should do it like that:

    Console.Write(string.Format("Hello, {0}", firstName));
    Console.Write(string.Format("! You have {0}", inbox));
    Console.Write(string.Format(" in your inbox. The temperature is {0}", degree));
    Console.Write(string.Format(" celsius."));

It also should work.

CodePudding user response:

You can use string.Format() to acheive your required functionality.

Console.Write(string.Format("Hello, {0}! You have {1} in your inbox. The temperature is {2} celsius.", firstName, inbox, degree));

CodePudding user response:

Please take a look on the following code code sample

It is not about Console.Write or Console.WriteLine

Console.Write("Hello, {0}", firstName); Console.Write("! You have {1}", inbox);

Here Statement 1 will work because the parameter passed 'firstName' is at 0 index but in Statement 2, it will throw an exception as the parameter 'inbox' is at position 0 and your code tries to find parameter at position 1 which is not available.

  •  Tags:  
  • c#
  • Related