Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make a generic number parser in C#? [duplicate]

To parse a string to an int, one calls Int32.Parse(string), for double, Double.Parse(string), for long, Int64.Parse(string), and so on..

Is it possible to create a method that makes it generic, for example, ParseString<T>(string)? where T can be Int32, Double, etc. I notice the number of types don't implement any common interface, and the Parse methods don't have any common parent.

Is there any way to achieve this or something similar to this?

like image 962
Louis Rhys Avatar asked May 28 '11 07:05

Louis Rhys


1 Answers

You'd basically have to use reflection to find the relevant static Parse method, invoke it, and cast the return value back to T. Alternatively, you could use Convert.ChangeType or get the relevant TypeDescriptor and associated TypeConverter.

A more limited but efficient (and simple, in some ways) approach would be to keep a dictionary from type to parsing delegate - cast the delegate to a Func<string, T> and invoke it. That would allow you to use different methods for different types, but you'd need to know the types you needed to convert to up-front.

Whatever you do, you won't be able to specify a generic constraint which would make it safe at compile-time though. Really you need something like my idea of static interfaces for that kind of thing. EDIT: As mentioned, there's the IConvertible interface, but that doesn't necessarily mean that you'll be able to convert from string. Another type could implement IConvertible without having any way of converting to that type from a string.

like image 136
Jon Skeet Avatar answered Sep 29 '22 12:09

Jon Skeet