TypeConverter vs. Convert vs. TargetType.Parse
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.
According to my personal preference and coding standards I choose between the following:
Convert
. I use this when I am absolutely sure that the values will be what I expect.int i = Convert.ToInt32("123");
TryParse
. I use this when I am handling user input. This also has the benefit to be able to use localized formatting when parsing.int i = 0; bool parsed = Int32.TryParse("123", out i);
There is also the possibility to use TryParseExact, where a certain pattern can be parsed. It can be useful in certain cases.
I'm going to post here 6 years late, because I think this is a good question and I am not satisfied with the existing answers.
The static Parse/TryParse
methods can be used only when you want to convert from string to the type that has those methods. (use TryParse
when you expect that the conversion may fail).
The point of System.Convert
is, as its documentation says, to convert from a base data type to another base data type. Note that with Convert you also have methods that take an Object
and figure out by themselves how to convert it.
As to System.ComponentModel.TypeConverter
, as the "typeconverter" stack overflow tag's documentation, they are used primarily to convert to and from string, when you want to provide a text representation of a class instance for use by designer serialization or for display in property grids