Home > other >  Dynamic Input direct from user in console
Dynamic Input direct from user in console

Time:10-02

In the following code;

for (int i = 0; i < 5; i  )
        {
            dynamic x;
            x = Console.ReadLine(); //readline methode returns string.
            Console.WriteLine(x.GetType().ToString());
        }

I tried to make a simple concept where the user would like to enter 5 elements of different type data then each time would show up.

the thing is, ReadLine will always return value as string, I can use convert but still, this will force the user to enter the only convert type.

I have been searching but don't really know what to do cause I don't know how to express the question.

Is there is another method that can take input dynamically from user or a property I don't know about.

CodePudding user response:

No. There's no other method to accept user inputs from the console. It will always be text/string.

You'll have to parse the inputs from Console.ReadLine() from a string to whatever type you need. Your problem is there's no way of knowing what the type is if you just have a string. If the user input "2" did she mean the number 2 (int) or did she actually mean "2" (string).

CodePudding user response:

You can have limited success, but for reasons pointed out in comments, it will be limited to a few primitive types. For example, a float input can't be discriminated between Float32 and Float64

for (int i = 0; i < 5; i  )
{
    var input = Console.ReadLine();

    dynamic x;
    if (int.TryParse(input, out int a))
        x = a;
    else if (float.TryParse(input, out float b))
        x = b;
    else if (input.Length == 1)
        x = input[0];
    else
        x = input;

    Console.WriteLine($"{x}: {x.GetType()}");
}

5
5: System.Int32
6.9
6.9: System.Single
f
f: System.Char
stri
stri: System.String

  • Related