Reputation: 23044
Is there any way to detect the type from a given string input?
Eg:
string input = "07/12/1999";
string DetectType( s ) { .... }
Type t = DetectType(input); // which would return me the matched datatype. i.e. "DateTime" in this case.
Would I have to write this from scratch?
Just wanted to check if anybody knows of a better way before I went about it.
Thanks!
Upvotes: 2
Views: 4662
Reputation: 3827
You got to know something about the expected type. If you do you could use TypeConverter e.g.:
public object DetectType(string stringValue)
{
var expectedTypes = new List<Type> {typeof (DateTime), typeof (int)};
foreach (var type in expectedTypes)
{
TypeConverter converter = TypeDescriptor.GetConverter(type);
if (converter.CanConvertFrom(typeof(string)))
{
try
{
// You'll have to think about localization here
object newValue = converter.ConvertFromInvariantString(stringValue);
if (newValue != null)
{
return newValue;
}
}
catch
{
// Can't convert given string to this type
continue;
}
}
}
return null;
}
Most system types have their own type converter, and you could write your own using the TypeConverter attribute on your class, and implementing your own converter.
Upvotes: 7
Reputation: 1500055
I'm pretty sure you'll have to write this from scratch - partly because it's going to be very strictly tailored to your requirements. Even a simple question such as whether the date you've given is December 7th or July 12th can make a big difference here... and whether your date formats are strict, what number formats you need to support etc.
I don't think I've ever come across anything similar - and to be honest, this sort of guesswork usually makes me nervous. It can be hard to get parsing right even when you know the data type, let alone when you're guessing at the data type to start with :(
Upvotes: 7