2

How can I dynamically parse a value entered by user to a certain type?

If I have a text box, where users might enter whatever they want, how can I parse that value dynamically and return the appropriate type?

 public dynamic ParseValue(dynamic value)
 {
     return //TO DO
 }

If user enters the following values:

  • 06.18.2015 10:23:00 // return DateTime
  • some text // return string
  • 10.23 //return double/decimal
  • true/True/false/False // return bool not string
  • 10 //return int

Is it the right way to use the type.TryParse, and check for each type if it's valid? Of course I'll have to check first if it's bool and then string, otherwise if the value is true/True/false/False will result in string rather than bool.

3

3 Answers 3

6

You do not need to use dynamic keyword. Because your source values always are string.

It is good to write generic method to parse values from string. You can use TypeConverter method of TypeDescriptor class to write this kind of method.

from this answer

public static T Convert<T>(this string input)
{
    var converter = TypeDescriptor.GetConverter(typeof(T));
    if(converter != null)
    {
        //Cast ConvertFromString(string text) : object to (T)
        return (T)converter.ConvertFromString(input);
    }
    return default(T);
}
2
  • 3
    You should rather flag the question duplicate than copy/paste...
    – Nam Bình
    Jul 4, 2015 at 8:14
  • @NamBình Sorry I thought that question is different because of mentioning dynamic keyword. Jul 4, 2015 at 8:43
0

Although I can not understand why you need this the following may work:

   // since user will enter text value should be string
    public dynamic ParseValue(string value)
    {
        DateTime tempDateTime;
        if (DateTime.TryParse(value, out tempDateTime))
        {
            return tempDateTime;
        }

        int tempInt;
        if(int.TryParse(value, out tempInt))
        {
            return tempInt;
        }

        // also process other types like double etc. before falling back to string
        return value;
    }
}

But I suspect this will be a solution since you will need to get the exact type to process return value in the caller function.

0

Yes imho you will need to use type.TryParse and build your own logic for type priorities

Generic TryParse

public dynamic ParseValue(string value)
 {
     return //TO DO
 }

Not the answer you're looking for? Browse other questions tagged or ask your own question.