vdh_ant
vdh_ant

Reputation: 13156

Using TypeDescriptor in place of TryParse

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

Upvotes: 1

Views: 927

Answers (1)

Pavel Minaev
Pavel Minaev

Reputation: 101555

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.

Upvotes: 2

Related Questions