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().

5
  • @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. Commented Apr 24, 2013 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? Commented Apr 24, 2013 at 13:56
  • @Bob- I have edited my post with more code examples. Thanks Commented Apr 24, 2013 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. :) Commented Apr 24, 2013 at 14:07
  • Maybe this answer might be helpful. Commented Apr 24, 2013 at 14:28

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.