TypeConverter Class (System.ComponentModel)

Switch View :
ScriptFree
.NET Framework Class Library
TypeConverter Class

Provides a unified way of converting types of values to other types, as well as for accessing standard values and subproperties.

Inheritance Hierarchy

System.Object
  System.ComponentModel.TypeConverter
    More...

Namespace:  System.ComponentModel
Assembly:  System (in System.dll)
Syntax

Visual Basic
<ComVisibleAttribute(True)> _
<HostProtectionAttribute(SecurityAction.LinkDemand, SharedState := True)> _
Public Class TypeConverter
C#
[ComVisibleAttribute(true)]
[HostProtectionAttribute(SecurityAction.LinkDemand, SharedState = true)]
public class TypeConverter
Visual C++
[ComVisibleAttribute(true)]
[HostProtectionAttribute(SecurityAction::LinkDemand, SharedState = true)]
public ref class TypeConverter
F#
[<ComVisibleAttribute(true)>]
[<HostProtectionAttribute(SecurityAction.LinkDemand, SharedState = true)>]
type TypeConverter =  class end

The TypeConverter type exposes the following members.

Constructors

  Name Description
Public method Supported by the XNA Framework TypeConverter Initializes a new instance of the TypeConverter class.
Top
Methods

  Name Description
Public method CanConvertFrom(Type) Returns whether this converter can convert an object of the given type to the type of this converter.
Public method CanConvertFrom(ITypeDescriptorContext, Type) Returns whether this converter can convert an object of the given type to the type of this converter, using the specified context.
Public method CanConvertTo(Type) Returns whether this converter can convert the object to the specified type.
Public method CanConvertTo(ITypeDescriptorContext, Type) Returns whether this converter can convert the object to the specified type, using the specified context.
Public method ConvertFrom(Object) Converts the given value to the type of this converter.
Public method ConvertFrom(ITypeDescriptorContext, CultureInfo, Object) Converts the given object to the type of this converter, using the specified context and culture information.
Public method ConvertFromInvariantString(String) Converts the given string to the type of this converter, using the invariant culture.
Public method ConvertFromInvariantString(ITypeDescriptorContext, String) Converts the given string to the type of this converter, using the invariant culture and the specified context.
Public method ConvertFromString(String) Converts the specified text to an object.
Public method ConvertFromString(ITypeDescriptorContext, String) Converts the given text to an object, using the specified context.
Public method ConvertFromString(ITypeDescriptorContext, CultureInfo, String) Converts the given text to an object, using the specified context and culture information.
Public method ConvertTo(Object, Type) Converts the given value object to the specified type, using the arguments.
Public method ConvertTo(ITypeDescriptorContext, CultureInfo, Object, Type) Converts the given value object to the specified type, using the specified context and culture information.
Public method ConvertToInvariantString(Object) Converts the specified value to a culture-invariant string representation.
Public method ConvertToInvariantString(ITypeDescriptorContext, Object) Converts the specified value to a culture-invariant string representation, using the specified context.
Public method ConvertToString(Object) Converts the specified value to a string representation.
Public method ConvertToString(ITypeDescriptorContext, Object) Converts the given value to a string representation, using the given context.
Public method ConvertToString(ITypeDescriptorContext, CultureInfo, Object) Converts the given value to a string representation, using the specified context and culture information.
Public method CreateInstance(IDictionary) Re-creates an Object given a set of property values for the object.
Public method CreateInstance(ITypeDescriptorContext, IDictionary) Creates an instance of the type that this TypeConverter is associated with, using the specified context, given a set of property values for the object.
Public method Supported by the XNA Framework Equals(Object) Determines whether the specified Object is equal to the current Object. (Inherited from Object.)
Protected method Supported by the XNA Framework Finalize Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Protected method GetConvertFromException Returns an exception to throw when a conversion cannot be performed.
Protected method GetConvertToException Returns an exception to throw when a conversion cannot be performed.
Public method GetCreateInstanceSupported() Returns whether changing a value on this object requires a call to the CreateInstance method to create a new value.
Public method GetCreateInstanceSupported(ITypeDescriptorContext) Returns whether changing a value on this object requires a call to CreateInstance to create a new value, using the specified context.
Public method Supported by the XNA Framework GetHashCode Serves as a hash function for a particular type. (Inherited from Object.)
Public method GetProperties(Object) Returns a collection of properties for the type of array specified by the value parameter.
Public method GetProperties(ITypeDescriptorContext, Object) Returns a collection of properties for the type of array specified by the value parameter, using the specified context.
Public method GetProperties(ITypeDescriptorContext, Object, Attribute[]) Returns a collection of properties for the type of array specified by the value parameter, using the specified context and attributes.
Public method GetPropertiesSupported() Returns whether this object supports properties.
Public method GetPropertiesSupported(ITypeDescriptorContext) Returns whether this object supports properties, using the specified context.
Public method GetStandardValues() Returns a collection of standard values from the default context for the data type this type converter is designed for.
Public method GetStandardValues(ITypeDescriptorContext) Returns a collection of standard values for the data type this type converter is designed for when provided with a format context.
Public method GetStandardValuesExclusive() Returns whether the collection of standard values returned from GetStandardValues is an exclusive list.
Public method GetStandardValuesExclusive(ITypeDescriptorContext) Returns whether the collection of standard values returned from GetStandardValues is an exclusive list of possible values, using the specified context.
Public method GetStandardValuesSupported() Returns whether this object supports a standard set of values that can be picked from a list.
Public method GetStandardValuesSupported(ITypeDescriptorContext) Returns whether this object supports a standard set of values that can be picked from a list, using the specified context.
Public method Supported by the XNA Framework GetType Gets the Type of the current instance. (Inherited from Object.)
Public method IsValid(Object) Returns whether the given value object is valid for this type.
Public method IsValid(ITypeDescriptorContext, Object) Returns whether the given value object is valid for this type and for the specified context.
Protected method Supported by the XNA Framework MemberwiseClone Creates a shallow copy of the current Object. (Inherited from Object.)
Protected method SortProperties Sorts a collection of properties.
Public method Supported by the XNA Framework ToString Returns a string that represents the current object. (Inherited from Object.)
Top
Remarks

The most common type of converter is one that converts to and from a text representation. The type converter for a class is bound to the class with a TypeConverterAttribute. Unless this attribute is overridden, all classes that inherit from this class use the same type converter as the base class.

Note Note

For general type system purposes, do not access a type converter directly. Instead, access the appropriate converter by using TypeDescriptor. For more information, see the code examples provided.

Note   For XAML purposes, a XAML processor searches for the TypeConverterAttribute directly, instead of going through TypeDescriptor. For cases where you do want a TypeDescriptor instance from code, or where you create a shared instance in WPF resources, it is acceptable to construct it directly without referencing TypeDescriptor or other reflection and type system support.

Classes derived from TypeConverter are often referenced as part of how a XAML processor converts an attribute or initialization text value from markup (which is inherently a string) and generates an object for a run-time representation. Custom type authors that intend to support a type conversion behavior for XAML typically implement a TypeConverter class that supports their own unique ConvertFrom behavior from a string. This behavior enables type conversion from the string provided as a XAML attribute value and provides a XAML processor with the support needed to create an object from the string, so that the object can be produced in a parsed object graph. Custom types or members of custom types are indicated by applying TypeConverterAttribute to the definitions, with the attribute referencing the custom TypeConverter implementation. For more information, see Type Converters for XAML Overview.

Note Note

The HostProtectionAttribute attribute applied to this type or member has the following Resources property value: SharedState. The HostProtectionAttribute does not affect desktop applications (which are typically started by double-clicking an icon, typing a command, or entering a URL in a browser). For more information, see the HostProtectionAttribute class or SQL Server Programming and Host Protection Attributes.

Notes to Inheritors

Inherit from TypeConverter to implement your own conversion requirements. When you inherit from this class, you can override the following methods:

Note Note

Your derived type might be marked as internal or private, but an instance of your type can be created with the TypeDescriptor class. Do not write insecure code by assuming the caller is trusted. Assume instead that callers might create instances of your type in partial trust.

For more information about type converters for general (non-XAML) purposes, see How to: Implement a Type Converter or Generalized Type Conversion.

Examples

The following code example shows how to create an instance of a type converter and bind it to a class. The class implementing the converter, MyClassConverter, must inherit from the TypeConverter class.

Visual Basic

<TypeConverter(GetType(MyClassConverter))> _
Public Class Class1
    ' Insert code here.
End Class 'MyClass



C#

[TypeConverter(typeof(MyClassConverter))]
 public class MyClass {
    // Insert code here.
}


Visual C++

public:
   [TypeConverter(Sample::MyClassConverter::typeid)]
   ref class MyClass
   {
      // Insert code here.
   };


When you have a property that has an enumeration, check to see whether an enumeration value is valid before setting the property. The next code example requires that an enumeration called MyPropertyEnum has been declared.

Visual Basic


Public WriteOnly Property MyProperty() As MyPropertyEnum
    Set
        ' Checks to see if the value passed is valid.
        If Not TypeDescriptor.GetConverter(GetType(MyPropertyEnum)).IsValid(value) Then
            Throw New ArgumentException()
        End If
        ' The value is valid. Insert code to set the property.
    End Set 
End Property



C#

public MyPropertyEnum MyProperty {
    set {
       // Checks to see if the value passed is valid.
       if (!TypeDescriptor.GetConverter(typeof(MyPropertyEnum)).IsValid(value)) {
          throw new ArgumentException();
       }
       // The value is valid. Insert code to set the property.
    }
 }


Visual C++

public:
   property MyPropertyEnum MyProperty 
   {
      void set( MyPropertyEnum value )
      {
         // Checks to see if the value passed is valid.
         if ( !TypeDescriptor::GetConverter( MyPropertyEnum::typeid )->IsValid( value ) )
         {
            throw gcnew ArgumentException;
         }
         // The value is valid. Insert code to set the property.
      }
   }


Another common type converter usage is to convert an object to a string. The following code example prints out the name of the Color stored in the variable c.

Visual Basic

Dim c As Color = Color.Red
Console.WriteLine(TypeDescriptor.GetConverter(c).ConvertToString(c))


C#

Color c = Color.Red;
    Console.WriteLine(TypeDescriptor.GetConverter(c).ConvertToString(c));


Visual C++

Color c = Color::Red;
Console::WriteLine( TypeDescriptor::GetConverter( c )->ConvertToString( c ) );


You can also use a type converter to convert a value from its name, as shown in the next code example.

Visual Basic

Dim c As Color = CType(TypeDescriptor.GetConverter(GetType(Color)).ConvertFromString("Red"), Color)


C#

Color c = (Color)TypeDescriptor.GetConverter(typeof(Color)).ConvertFromString("Red");


Visual C++

Color c =  (Color)(TypeDescriptor::GetConverter( Color::typeid )->ConvertFromString( "Red" ));


In the following code example, you can use a type converter to print out the set of standard values that the object supports.

Visual Basic

Dim c As Color
For Each c In  TypeDescriptor.GetConverter(GetType(Color)).GetStandardValues()
    Console.WriteLine(TypeDescriptor.GetConverter(c).ConvertToString(c))
Next c


C#

foreach(Color c in TypeDescriptor.GetConverter(typeof(Color)).GetStandardValues()) {
    Console.WriteLine(TypeDescriptor.GetConverter(c).ConvertToString(c));
 }


Visual C++

for each ( Color c in TypeDescriptor::GetConverter( Color::typeid )->GetStandardValues() )
{
   Console::WriteLine( TypeDescriptor::GetConverter( c )->ConvertToString( c ) );
}


Version Information

.NET Framework

Supported in: 4, 3.5, 3.0, 2.0, 1.1, 1.0

.NET Framework Client Profile

Supported in: 4, 3.5 SP1
Platforms

Windows 7, Windows Vista SP1 or later, Windows XP SP3, Windows XP SP2 x64 Edition, Windows Server 2008 (Server Core not supported), Windows Server 2008 R2 (Server Core supported with SP1 or later), Windows Server 2003 SP2

The .NET Framework does not support all versions of every platform. For a list of the supported versions, see .NET Framework System Requirements.
Thread Safety

Any public static (Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe.
See Also

Reference

Other Resources

Inheritance Hierarchy

System.Object
  System.ComponentModel.TypeConverter
    Microsoft.VisualBasic.Activities.XamlIntegration.VisualBasicSettingsConverter
    Microsoft.VisualBasic.ApplicationServices.BuiltInRoleConverter
    System.Activities.XamlIntegration.TypeConverterBase
    System.ComponentModel.BaseNumberConverter
    System.ComponentModel.BooleanConverter
    System.ComponentModel.CharConverter
    System.ComponentModel.CollectionConverter
    System.ComponentModel.CultureInfoConverter
    System.ComponentModel.DateTimeConverter
    System.ComponentModel.DateTimeOffsetConverter
    System.ComponentModel.EnumConverter
    System.ComponentModel.ExpandableObjectConverter
    System.ComponentModel.GuidConverter
    System.ComponentModel.MultilineStringConverter
    System.ComponentModel.NullableConverter
    System.ComponentModel.ReferenceConverter
    System.ComponentModel.StringConverter
    System.ComponentModel.TimeSpanConverter
    System.ComponentModel.TypeListConverter
    System.Configuration.ConfigurationConverterBase
    System.Diagnostics.Design.LogConverter
    System.Drawing.ColorConverter
    System.Drawing.FontConverter
    System.Drawing.FontConverter.FontNameConverter
    System.Drawing.ImageConverter
    System.Drawing.ImageFormatConverter
    System.Drawing.PointConverter
    System.Drawing.RectangleConverter
    System.Drawing.SizeConverter
    System.Drawing.SizeFConverter
    System.Resources.ResXFileRef.Converter
    System.Security.Authentication.ExtendedProtection.ExtendedProtectionPolicyTypeConverter
    System.ServiceModel.Discovery.Configuration.DiscoveryVersionConverter
    System.ServiceModel.XamlIntegration.EndpointIdentityConverter
    System.ServiceModel.XamlIntegration.ServiceXNameTypeConverter
    System.ServiceModel.XamlIntegration.XPathMessageContextTypeConverter
    System.UriTypeConverter
    System.Web.Configuration.LowerCaseStringConverter
    System.Web.UI.Design.DataBindingCollectionConverter
    System.Web.UI.Design.DataColumnSelectionConverter
    System.Web.UI.Design.DataFieldConverter
    System.Web.UI.Design.DataMemberConverter
    System.Web.UI.Design.DataSourceConverter
    System.Web.UI.Design.DataSourceViewSchemaConverter
    System.Web.UI.Design.ExpressionsCollectionConverter
    System.Web.UI.Design.MobileControls.Converters.DataFieldConverter
    System.Web.UI.Design.MobileControls.Converters.DataMemberConverter
    System.Web.UI.Design.SkinIDTypeConverter
    System.Web.UI.Design.WebControls.DataSourceIDConverter
    System.Web.UI.WebControls.FontNamesConverter
    System.Web.UI.WebControls.FontUnitConverter
    System.Web.UI.WebControls.StringArrayConverter
    System.Web.UI.WebControls.UnitConverter
    System.Windows.Controls.DataGridLengthConverter
    System.Windows.CornerRadiusConverter
    System.Windows.CultureInfoIetfLanguageTagConverter
    System.Windows.DeferrableContentConverter
    System.Windows.DialogResultConverter
    System.Windows.DurationConverter
    System.Windows.DynamicResourceExtensionConverter
    System.Windows.ExpressionConverter
    System.Windows.FigureLengthConverter
    System.Windows.FontSizeConverter
    System.Windows.FontStretchConverter
    System.Windows.FontStyleConverter
    System.Windows.FontWeightConverter
    System.Windows.Forms.AxHost.StateConverter
    System.Windows.Forms.CursorConverter
    System.Windows.Forms.DataGridPreferredColumnWidthTypeConverter
    System.Windows.Forms.DataGridViewCellStyleConverter
    System.Windows.Forms.KeysConverter
    System.Windows.Forms.Layout.TableLayoutSettingsTypeConverter
    System.Windows.Forms.LinkArea.LinkAreaConverter
    System.Windows.Forms.LinkConverter
    System.Windows.Forms.ListBindingConverter
    System.Windows.Forms.OpacityConverter
    System.Windows.Forms.PaddingConverter
    System.Windows.Forms.ScrollableControl.DockPaddingEdgesConverter
    System.Windows.Forms.SelectionRangeConverter
    System.Windows.Forms.TreeNodeConverter
    System.Windows.GridLengthConverter
    System.Windows.Input.CommandConverter
    System.Windows.Input.CursorConverter
    System.Windows.Input.InputScopeConverter
    System.Windows.Input.InputScopeNameConverter
    System.Windows.Input.KeyConverter
    System.Windows.Input.KeyGestureConverter
    System.Windows.Input.ModifierKeysConverter
    System.Windows.Input.MouseActionConverter
    System.Windows.Input.MouseGestureConverter
    System.Windows.Int32RectConverter
    System.Windows.KeySplineConverter
    System.Windows.KeyTimeConverter
    System.Windows.LengthConverter
    System.Windows.Markup.DependencyPropertyConverter
    System.Windows.Markup.EventSetterHandlerConverter
    System.Windows.Markup.NameReferenceConverter
    System.Windows.Markup.RoutedEventConverter
    System.Windows.Markup.SetterTriggerConditionValueConverter
    System.Windows.Markup.TemplateKeyConverter
    System.Windows.Markup.XmlLanguageConverter
    System.Windows.Media.Animation.RepeatBehaviorConverter
    System.Windows.Media.BrushConverter
    System.Windows.Media.CacheModeConverter
    System.Windows.Media.ColorConverter
    System.Windows.Media.Converters.BaseIListConverter
    System.Windows.Media.DoubleCollectionConverter
    System.Windows.Media.FontFamilyConverter
    System.Windows.Media.GeometryConverter
    System.Windows.Media.ImageSourceConverter
    System.Windows.Media.Int32CollectionConverter
    System.Windows.Media.MatrixConverter
    System.Windows.Media.Media3D.Matrix3DConverter
    System.Windows.Media.Media3D.Point3DCollectionConverter
    System.Windows.Media.Media3D.Point3DConverter
    System.Windows.Media.Media3D.Point4DConverter
    System.Windows.Media.Media3D.QuaternionConverter
    System.Windows.Media.Media3D.Rect3DConverter
    System.Windows.Media.Media3D.Size3DConverter
    System.Windows.Media.Media3D.Vector3DCollectionConverter
    System.Windows.Media.Media3D.Vector3DConverter
    System.Windows.Media.PathFigureCollectionConverter
    System.Windows.Media.PixelFormatConverter
    System.Windows.Media.PointCollectionConverter
    System.Windows.Media.RequestCachePolicyConverter
    System.Windows.Media.TransformConverter
    System.Windows.Media.VectorCollectionConverter
    System.Windows.PointConverter
    System.Windows.PropertyPathConverter
    System.Windows.RectConverter
    System.Windows.SizeConverter
    System.Windows.StrokeCollectionConverter
    System.Windows.TemplateBindingExpressionConverter
    System.Windows.TemplateBindingExtensionConverter
    System.Windows.TextDecorationCollectionConverter
    System.Windows.ThicknessConverter
    System.Windows.VectorConverter
    System.Workflow.ComponentModel.Design.ActivityBindTypeConverter
    System.Xaml.Schema.XamlTypeTypeConverter
Community Content

wmarkjones
Requirements for a generalized Type-conversion strategy in .NET
To better understand the underlying requirements regarding a generalized approach to Type conversion in .NET, please see my answer to a specific, related question at: http://stackoverflow.com/questions/312858/how-can-i-convert-types-at-runtime/7942350#7942350