-2

Is there a way to write code so that when a user gives input, either a string or a number, that the program will choose the most appropriate of the available variables that have been declared?

Pseudocode example:

static void Main()
{
    int A;
    string B;

    Console.Write("enter something: ");

    if (user enters a number)
        A = int.Parse(Console.ReadLine());
    else
        B = Console.ReadLine();
}
Uwe Keim
  • 39,551
  • 56
  • 175
  • 291
Tommy
  • 69
  • 4

2 Answers2

3

Simply said, since Console.ReadLine is the way to receive user input, and since it always returns a string, no matter what: No, you have to parse the string for being a number yourself, and in turn assign it to the most fitting variable yourself.

You can do that with int.TryParse, which returns true if the given string could be parsed into a (integral) number, assigned to the second out parameter in the same line:

static void Main()
{
    Console.Write("enter something: ");
    string B = Console.ReadLine();
    if (int.TryParse(B, out int A))
        Console.WriteLine($"Yay, user entered number {A}.");
    else
        Console.WriteLine($"Nay, user entered a boring string {B}.");
}
Ray
  • 7,940
  • 7
  • 58
  • 90
1

You can let int.TryParse() decide:

int A;
string B;

string userinput = Console.ReadLine();

// if parsing to int fails, assign to B
if (!int.TryParse(userinput, out A)
{
    B = userinput;
}
Filburt
  • 17,626
  • 12
  • 64
  • 115