What mechanisms does .Net provide to convert one type to another
Type conversion is usually possible in one of the following ways:
Using explicit methods in source type like:
There is usually a corresponding explicit or implicit operator that does the
same conversion. The operators are however not available in VB.Net.
Using FromXXX static methods exposed in the destination type:
Using implicit or explicit operators defined in the source or destination
type. This will allow you to perform implicit or explicit casts from the
source type to the destination type.
There is usually a corresponding ToXXX method that does the same conversion.
You can use either this or the ToXXX methods in C#.
Some types come with TypeConverters that allow you to convert to or convert
from another type. This conversion is usually not documented and can be
discovered only by writing some test code.
For example, the System.Drawing.Icon type’s TypeConverter converts the Icon
into a byte. You can use this functionality in your code as follows:
It’s usually time consuming to figure out whether a TypeConverter’s
ConvertTo or ConvertFrom method can perform the necessary conversion.
The attached TypeConverterLookup tool
lets you figure that out easily on any type declared in any assembly available in the GAC or available in the same directory as the tool’s exe. If you have types in custom assemblies, then just copy over that assembly to the same directory as the tool, you can then specify the type in the tool.