views:

56

answers:

2

Is there any method to detect the type from a given string input?

Eg: string s = "07/12/1999";

I need a method like string DetectType( s ) { .... } 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!

+3  A: 

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 :(

Jon Skeet
That's Sir Jon Skeet talking.
yonan2236
Well, I'd have to agree.. Was just wary before I started out. I guess now I'll have to. Thanks!
conqenator
I'd wager your unit tests and test data (which you will sooooo need to have) will be 10x times longer than the method code itself lol :)
MattC
A: 

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.

Amittai Shapira
Oh, Hmmm.. will dive deeper into TypeConverter. Thanks for de tips.
conqenator