5
\$\begingroup\$

My code is very simple, it asks for an input then stores the input. I am new to c# and wanted to know if it was possible to both ask and accept the input on one line.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApplication
{
    class Program
    {
        static void Main()
        {
            var input = GetInput();
            Console.WriteLine("Your input:\n{0}", input);

        }
        static string GetInput() 
        {
            Console.WriteLine("Please input somthing");
            var input = Console.ReadLine();
            return input;    

        }
    }
}

All feedback welcome!

\$\endgroup\$
4
\$\begingroup\$

You sure can, you can use something even smaller such as:

using System;

namespace ConsoleApplication
{
    class Program
    {
        static void Main()
        {
            Console.WriteLine("Please input something");
            Console.WriteLine("Your input: \n{0}", Console.ReadLine());
            Console.ReadLine(); //stops the console from closing
        }
    }
}
\$\endgroup\$
  • \$\begingroup\$ Can be shorter by removing the extra usings \$\endgroup\$ – Mihai-Daniel Virna Jul 15 '16 at 14:40
  • \$\begingroup\$ Since you're only using the System.Console class out of the System namespace, this could be even shorter with using static System.Console; - see stackoverflow.com/a/31852390/3140 \$\endgroup\$ – Jacob Krall Jul 15 '16 at 17:04
3
\$\begingroup\$

Yep, that's totally fine.

Just in case you weren't aware, you might want to add Console.ReadLine(); to the end of your Main() function so that the window stays open until you press enter again. Otherwise the program will print "Your input..." to the screen, reach the end of the Main() function, see that there is nothing else for it to do and exit before you have even had a chance to look at what it printed!

\$\endgroup\$
  • 3
    \$\begingroup\$ You could just start your program with Ctrl+F5, which will leave the window open after the application completes. \$\endgroup\$ – forsvarir Jul 15 '16 at 11:24

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.