Pranav Raj
Pranav Raj

Reputation: 873

Reading (and parsing) different types of input from console using a single function in C#

I want to write a generic function which reads and parses different kinds of input.

I have to take multiple inputs from user and the datatypes of theses inputs are different. I want to make a function which ideally should do the following:

Can you please suggest me a way to do this in C#.

Upvotes: 0

Views: 113

Answers (1)

mybirthname
mybirthname

Reputation: 18127

    public static T ConvertTo<T>(object value)
    {
        try
        {
            return (T)Convert.ChangeType(value, typeof(T));
        }
        catch(Exception ex)
        {
            return (T)(typeof(T).IsValueType ? Activator.CreateInstance(typeof(T)) : null);
        }

    }

    static void Main(string[] args)
    {
        Console.Write("Enter int: ");
        int a = ConvertTo<int>(Console.ReadLine());

        Console.Write("Enter decimal: ");
        decimal b = ConvertTo<decimal>(Console.ReadLine());

        Console.Write("Enter double: ");
        double c = ConvertTo<double>(Console.ReadLine());

        Console.Write("Enter Date Time: ");
        DateTime d = ConvertTo<DateTime>(Console.ReadLine());

        Console.WriteLine(a + ", " + b + ", " + c + ", " + d);
    }

Here this is what I can think of closest to your requirments.

Upvotes: 1

Related Questions