TypeConverter vs. Convert vs. TargetType.Parse

Viewed 16756

As far as I know, there are at least 3 ways to convert data types in .NET:


using System.ComponentModel.TypeConverter

var conv = System.ComponentModel.TypeDescriptor.GetConverter(typeof(int));
var i1 = (int)conv.ConvertFrom("123");

using System.Convert.ChangeType():

var i2 = (int) Convert.ChangeType("123", typeof (int));

using the Parse/TryParse methods of the destination type:

var i3 = int.Parse("123"); // or TryParse



Are there any guidelines or rules-of-thumb when to use which method to convert between the .NET base data types (especially from string to some other data type)?

7 Answers

Convert

Convert class uses the IConvertible methods implemented in the target type.

Unfortunately, implementing IConvertible means writing lots of boilerplate code and Convert.ChangeType causes boxing if the target type is a struct.

TypeConverterAttribute

TypeDescriptor.GetConverter uses the TypeConverterAttribute and IMHO offers both a better API to convert a type and a more elegant way to make a type convertible. But it suffers the same performance issues with the Convert class, caused by the methods not being generic.

Parse/TryParse

Using T.Parse/T.TryParse methods is the de facto way of creating an object from a string since it doesn't involve unnecessary boxing. They also usually have overloads that provide greater control of how to parse the string.

TryParse methods allow you to handle cases where the string you want to parse is obtained from user input or another mean that doesn't guarantee a properly formatted string, without throwing exceptions.


So you should call the type's Parse/TryParse methods when you can and fallback to the other ways only when you don't know the target type in the compile time, i.e. when you only have a Type object that represents your target type.

You can also have look at my little library called ValueString that finds the most suitable parsing method of a type and uses it to parse the string.

Another late answer. I have an application where I was using some code that looks like this:

var finalValue = Convert.ChangeType(sourceValue, targetProperty.PropertyType);

sourceValue would be a string representation of what I wanted which normally would be a primitive under a wrapper class. This way would work with regular data types. Even with entire classes. However, one day I stupidly decided to change the datatype of a property that was a double to a nullable one double? guess what? boom!

invalid cast from string to nullable double

This is the perfect scenario where you should use the TypeConverter class as follows:

void Main()
{
    var ss = new[] {"2.01", "3.99", ""};
    var conv = TypeDescriptor.GetConverter(typeof(A).GetProperties().First().PropertyType);
    Console.WriteLine(string.Join(",", ss.Select(s => conv.ConvertFrom(s))));
}

class A {
    public double? b {get; set;}
}

//2.01,3.99,
Related