Search code examples
c#.nettypestypeconverter

C# TypeConverters and IsValid


I am trying to use System.ComponentModel.TypeConverter to cast a bunch of System.Strings to different types. These Strings may or may not be in a valid format for the TypeConverter, so I'd like to find a way to check their validity before attempting the type conversion (to avoid having to rely on catching a System.FormatException to indicate that the String is not in the correct format).

Great, that's why TypeConverters have an IsValid() method, right? Well I'm running into a problem where IsValid() will return true, but when I call ConvertFromString(), it throws an exception. Here is some code to reproduce the issue:

        System.ComponentModel.DateTimeConverter DateConversion = 
            new System.ComponentModel.DateTimeConverter();

        String TheNumberZero = "0";

        if (DateConversion.IsValid(TheNumberZero))
            Console.WriteLine(DateConversion.
                ConvertFromString(TheNumberZero).ToString());
        else
            Console.WriteLine("Invalid.");

When I run this, the line

Console.WriteLine(DateConversion.
    ConvertFromString(TheNumberZero).ToString());

throws a System.FromatException with the message

0 is not a valid value for DateTime.

What is the purpose of the IsValid() method if not to check the conversion input before attempting a type conversion? Is there some way I can check the String's validity short of having to catch the FormatException?


Solution

  • The documentation is your friend:

    The IsValid method is used to validate a value within the type rather than to determine if value can be converted to the given type. For example, IsValid can be used to determine if a given value is valid for an enumeration type. For an example, see EnumConverter.

    You can write your own WillConvertSucceed method by wrapping the ConvertTo and ConvertFrom methods in exception blocks.