Michelangelo
Michelangelo

Reputation: 43

How can i write a variabile in the Function Console.Write in this case?

I am learning c# for fun! I have experience with the c coding and I have a really stupid question, in my console application, I want to show a variable called "x" using Console.Write but I want to show it with also a text line in the same function. If you don't understand I attach here the code that i did.

  using System;

namespace Media_Random
{
    class MainClass
    {
        public static void Main (string[] args)
        {
            Console.Write ("This program makes an avarage of 3 numbers chosen randomly\n");
            int a = 1;
            int b = 10;
            Random random = new Random();
            int x=random.Next(a,b);
            Console.Write ("the first value is\n",x); //i want to in write in the console the value x there but it doesn't work 
        }
    }

}

I hope that showing the code it will be more simple to understand the problem.

Upvotes: 0

Views: 69

Answers (3)

wnvko
wnvko

Reputation: 2120

One more thing. If you are using VS 2015 you can change string.Format with $ like this:

Console.WriteLine($"the first value is {x}");

Adding $ in front of the open quotes allows you to put the variables inside the placeholders directly. From my point of view this syntax is much more easier and more readable.

Upvotes: 0

Dmitrii Bychenko
Dmitrii Bychenko

Reputation: 186813

Try this:

 Console.Write("the first value is {0}\n", x); 

Please, notice that the overloaded Console.Write you've used wants format string with placeholder for x: {0} in the context.

Further suggestion: Console has as special method WriteLine that's why you, probably, don't want put

 Console.Write("...\n");

instead of

 Console.WriteLine("...");

Upvotes: 1

mrogal.ski
mrogal.ski

Reputation: 5930

If you want to do this to display it in this format :

the first value is
X

Then use this method :

Console.Write(string.Format("the first value is\n{0}", x));

But if you prefer to display int in this format :

the first value is X
<newlinehere>

Then use this method :

Console.WriteLine(string.Format("the first value is {0}\n', x));

You should read this if you want to format it in the different way.

Upvotes: 0

Related Questions