views:

201

answers:

1

Hi Guys

I am trying to replicate TryParse for generic types and thought that TypeDescriptor might give me what I am after. So I came up with the following test case but it is failing, just wondering if anyone knows where I am going wrong.

    [TestMethod]
    public void Test()
    {
        string value = "Test";
        Guid resultValue;
        var result = this.TryConvert(value, out resultValue); 
    } 

    public bool TryConvert<T>(string value, out T resultValue)
    { 
        var converter = System.ComponentModel.TypeDescriptor.GetConverter(typeof(T));
        if (converter.IsValid(value))
        {
            resultValue = (T)converter.ConvertFrom(value);
            return true;
        }
        resultValue = default(T);
        return false;
    }

Note, I don't want to use a try catch block.

Cheers Anthony

+2  A: 

From MSDN documentation for TypeConverter.IsValid:

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.

So it will only check the type of the value, not whether the value is correct input that can be parsed.

Also see this Connect ticket.

Pavel Minaev
EnumConverter, NullableConverter, and UriTypeConverter are the only ones that actually make use of IsValid.
sixlettervariables