11

Using TypeConverter.ConvertFromString(), I need to supply a custom format when parsing data from a string (for example, with DateTime: "ddMMyyyy" or "MMMM dd, yyyy").

TypeConverter.ConvertFromString() has the following overload:

public object ConvertFromString(ITypeDescriptorContext context, 
                                CultureInfo culture, 
                                string text);

I checked up on MSDN about ITypeDescriptorContext.

The ITypeDescriptorContext interface provides contextual information about a component. ITypeDescriptorContext is typically used at design time to provide information about a design-time container. This interface is commonly used in type conversion.

This sounds like what I need to use but I cannot find any examples anywhere.

I am using the following generic method:

public T ParseValue<T>(string value)
{
    return (T)TypeDescriptor.GetConverter(typeof(T)).ConvertFromString(value);
}

Example calling code:

DateTime date = ParseValue<DateTime>("02062001");
decimal amount = ParseValue<decimal>("1.3423");

I want to be able to parse some kind of generic formatting info into this ParseValue() method which can be used by ConvertFromString().

Dave New
  • 38,496
  • 59
  • 215
  • 394
  • @Bob- Because sometimes I will be parsing from a string to other data types (not just `DateTime`). I need to use `TypeDescriptor` so that I can get the appropriate parsing mechanism at runtime. – Dave New Apr 24 '13 at 13:51
  • I'm confused, you want to convert a DateTime, being represented as a string, to other data types? So like to an int? – Bob. Apr 24 '13 at 13:56
  • @Bob- I have edited my post with more code examples. Thanks – Dave New Apr 24 '13 at 14:05
  • Ah, I see, you're looking for a generic string converter that changes it to the appropriate data type, should really change your title to reflect that. :) – Bob. Apr 24 '13 at 14:07
  • Maybe [this answer](http://stackoverflow.com/a/1833128/1466627) might be helpful. – Bob. Apr 24 '13 at 14:28

1 Answers1

4

You can create a custom CultureInfo , holding your format.

Another solution would be to Wrap conversion in some helper method that would use DateTime.Parse for dates and TypeConverter for other types.

alex
  • 12,464
  • 3
  • 46
  • 67
  • 1
    I have considered that (I would also need to specify number formats when parsing decimals, negatives, etc), but it seems like an overkill to have to create a dummy CultureInfo object and just overwrite some relevant property. And then what is `ITypeDescriptorContext` actually for? Thanks for the reply :) – Dave New Apr 24 '13 at 13:58