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


i want write generic function reads , parses different kinds of input.

i have take multiple inputs user , datatypes of theses inputs different. want make function ideally should following:

  • takes datatype argument. let x
  • do x.tryparse(console.readline()) , return output

can please suggest me way in c#.

    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 = 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 can think of closest requirments.


Comments

Popular posts from this blog

c++ - OpenMP unpredictable overhead -

ruby on rails - RuntimeError: Circular dependency detected while autoloading constant - ActiveAdmin.register Role -

javascript - Wordpress slider, not displayed 100% width -