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!
2 Answers 2
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
}
}
}
-
\$\begingroup\$ Can be shorter by removing the extra
using
s \$\endgroup\$Mihai-Daniel Virna– Mihai-Daniel Virna2016年07月15日 14:40:21 +00:00Commented Jul 15, 2016 at 14:40 -
\$\begingroup\$ Since you're only using the
System.Console
class out of theSystem
namespace, this could be even shorter withusing static System.Console;
- see stackoverflow.com/a/31852390/3140 \$\endgroup\$Jacob Krall– Jacob Krall2016年07月15日 17:04:34 +00:00Commented Jul 15, 2016 at 17:04
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!
-
3\$\begingroup\$ You could just start your program with Ctrl+F5, which will leave the window open after the application completes. \$\endgroup\$forsvarir– forsvarir2016年07月15日 11:24:37 +00:00Commented Jul 15, 2016 at 11:24