Live Chat Icon For mobile
Live Chat Icon

What mechanisms does .Net provide to convert one type to another

Platform: WinForms| Category: Tips

Type conversion is usually possible in one of the following ways:

1) Using explicit methods in source type like:

  public class SizeF
  {
    ...
    public Size ToSize();
  }

There is usually a corresponding explicit or implicit operator that does the

same conversion. The operators are however not available in VB.Net.

2) Using FromXXX static methods exposed in the destination type:

  class Image
  {
    ...
    public static Image FromStream(Stream);
  }

3) 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.

  SizeF sizeF = size; // Possible because type Size has an implicit type conversion operator that converts a Size to SizeF

  PointF pointF = (PointF)sizeF; // Possible because type SizeF has an explicit type conversion operator that converts a SizeF to PointF.

There is usually a corresponding ToXXX method that does the same conversion.
You can use either this or the ToXXX methods in C#.

4) Using TypeConverters.
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:

  TypeConverter tc = TypeDescriptor.GetConverter(typeof(System.Drawing.Icon));
  byte[] blob = tc.ConvertTo(myIcon, typeof(byte[]));

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.

Share with

Share on twitter
Share on facebook
Share on linkedin

Related FAQs

Couldn't find the FAQs you're looking for?

Please submit your question and answer.