Sss Sss - 10 months ago 39
C# Question

how to write two string and their two variables values using 1 Console.Writeline() in c#

I am switched to c# and want to write two variable value in one line using Console.Writeline() function in c#.

In c++ i could have done it like this:

cout<<"symbol : "<<symbol<<"frequency : "<<frequency<<endl;

which will print :

symbol : a frequency : 10

I tried to do in c# but it just print only first variable, I done like this :

Console.WriteLine("Symbol : " +parentNode.symbol ,"frequency is : " + code );

which just print only
symbol : 10
don't print frequency.

I tried to two Console.WriteLine() for both but that change the line.

Any help how to achieve so ?

Answer Source

What I think you're trying to achieve can be done like this:

Console.WriteLine("Symbol : " + parentNode.symbol + " frequency is : " + code);

i.e. Console.WriteLine(string)

But a better way would be to use the following overload Console.WriteLine(string, params object[]):

Console.WriteLine("Symbol : {0} frequency is : {1}", parentNode.symbol, code);

And as of C# 6, you can use string interpolation (note the $ before the string):

Console.WriteLine($"Symbol : {parentNode.symbol} frequency is : {code}");

The problem is that your code is using the second overload of Console.WriteLine but your code is not written in a way that this method can understand it.

For more information, see the MSDN documentation on the Console.WriteLine methods: