Skip to main content
.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
SystemObject
  System.ComponentModelTypeConverter
    More...

Namespace:   System.ComponentModel
Assembly:  System (in System.dll)
Syntax
<[%$TOPIC/x1z9x06x_en-us_VS_110_2_0_0_0_0%](True)> _
<[%$TOPIC/x1z9x06x_en-us_VS_110_2_0_0_0_1%]([%$TOPIC/x1z9x06x_en-us_VS_110_2_0_0_0_2%].LinkDemand, SharedState := True)> _
Public Class TypeConverter
[[%$TOPIC/x1z9x06x_en-us_VS_110_2_0_1_0_0%](true)]
[[%$TOPIC/x1z9x06x_en-us_VS_110_2_0_1_0_1%]([%$TOPIC/x1z9x06x_en-us_VS_110_2_0_1_0_2%].LinkDemand, SharedState = true)]
public class TypeConverter
[[%$TOPIC/x1z9x06x_en-us_VS_110_2_0_2_0_0%](true)]
[[%$TOPIC/x1z9x06x_en-us_VS_110_2_0_2_0_1%]([%$TOPIC/x1z9x06x_en-us_VS_110_2_0_2_0_2%]::LinkDemand, SharedState = true)]
public ref class TypeConverter
[<[%$TOPIC/x1z9x06x_en-us_VS_110_2_0_3_0_0%](true)>]
[<[%$TOPIC/x1z9x06x_en-us_VS_110_2_0_3_0_1%]([%$TOPIC/x1z9x06x_en-us_VS_110_2_0_3_0_2%].LinkDemand, SharedState = true)>]
type TypeConverter =  class end

The TypeConverter type exposes the following members.

Constructors
  NameDescription
Public method Supported by the XNA Framework TypeConverterInitializes a new instance of the TypeConverter class.
Top
Methods
  NameDescription
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 FinalizeAllows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Protected method GetConvertFromExceptionReturns an exception to throw when a conversion cannot be performed.
Protected method GetConvertToExceptionReturns an exception to throw when a conversion cannot be performed.
Public method GetCreateInstanceSupportedReturns 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 GetHashCodeServes as the default hash function. (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 GetPropertiesSupportedReturns whether this object supports properties.
Public method GetPropertiesSupported(ITypeDescriptorContext)Returns whether this object supports properties, using the specified context.
Public method GetStandardValuesReturns 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 GetStandardValuesExclusiveReturns 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 GetStandardValuesSupportedReturns 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 GetTypeGets 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 MemberwiseCloneCreates a shallow copy of the current Object. (Inherited from Object.)
Protected method SortPropertiesSorts a collection of properties.
Public method Supported by the XNA Framework ToStringReturns 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.

NoteNote

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.

NoteNote

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:

NoteNote

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.

<TypeConverter(GetType(MyClassConverter))> _
Public Class Class1
    ' Insert code here. 
End Class 'MyClass
[TypeConverter(typeof(MyClassConverter))]
 public class MyClass {
    // Insert code here.
}
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.

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
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.
    }
 }
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.

Dim c As Color = Color.Red
Console.WriteLine(TypeDescriptor.GetConverter(c).ConvertToString(c))
Color c = Color.Red;
    Console.WriteLine(TypeDescriptor.GetConverter(c).ConvertToString(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.

Dim c As Color = CType(TypeDescriptor.GetConverter(GetType(Color)).ConvertFromString("Red"), Color)
Color c = (Color)TypeDescriptor.GetConverter(typeof(Color)).ConvertFromString("Red");
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.

Dim c As Color
For Each c In  TypeDescriptor.GetConverter(GetType(Color)).GetStandardValues()
    Console.WriteLine(TypeDescriptor.GetConverter(c).ConvertToString(c))
Next c
foreach(Color c in TypeDescriptor.GetConverter(typeof(Color)).GetStandardValues()) {
    Console.WriteLine(TypeDescriptor.GetConverter(c).ConvertToString(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.6, 4.5, 4, 3.5, 3.0, 2.0, 1.1, 1.0

.NET Framework Client Profile

Supported in: 4, 3.5 SP1

Supported in: Windows Phone 8.1

Supported in: Windows Phone Silverlight 8.1

Supported in: Windows Phone Silverlight 8
Platforms

Windows Phone 8.1, Windows Phone 8, Windows 8.1, Windows Server 2012 R2, Windows 8, Windows Server 2012, Windows 7, Windows Vista SP2, Windows Server 2008 (Server Core Role not supported), Windows Server 2008 R2 (Server Core Role supported with SP1 or later; Itanium not supported)

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.
Inheritance Hierarchy
SystemObject
  System.ComponentModelTypeConverter
     Microsoft.VisualBasic.Activities.XamlIntegrationVisualBasicSettingsConverter
     Microsoft.VisualBasic.ApplicationServicesBuiltInRoleConverter
     System.Activities.XamlIntegrationAssemblyReferenceConverter
     System.Activities.XamlIntegrationDynamicUpdateMapConverter
     System.Activities.XamlIntegrationDynamicUpdateMapItemConverter
     System.Activities.XamlIntegrationImplementationVersionConverter
     System.Activities.XamlIntegrationTypeConverterBase
     System.Activities.XamlIntegrationWorkflowIdentityConverter
     System.ComponentModelBaseNumberConverter
     System.ComponentModelBooleanConverter
     System.ComponentModelCharConverter
     System.ComponentModelCollectionConverter
     System.ComponentModelCultureInfoConverter
     System.ComponentModelDateTimeConverter
     System.ComponentModelDateTimeOffsetConverter
     System.ComponentModelEnumConverter
     System.ComponentModelExpandableObjectConverter
     System.ComponentModelGuidConverter
     System.ComponentModelMultilineStringConverter
     System.ComponentModelNullableConverter
     System.ComponentModelReferenceConverter
     System.ComponentModelStringConverter
     System.ComponentModelTimeSpanConverter
     System.ComponentModelTypeListConverter
     System.ConfigurationConfigurationConverterBase
     System.Diagnostics.DesignLogConverter
     System.DrawingColorConverter
     System.DrawingFontConverter
     System.DrawingFontConverterFontNameConverter
     System.DrawingImageConverter
     System.DrawingImageFormatConverter
     System.DrawingPointConverter
     System.DrawingRectangleConverter
     System.DrawingSizeConverter
     System.DrawingSizeFConverter
     System.ResourcesResXFileRefConverter
     System.Security.Authentication.ExtendedProtectionExtendedProtectionPolicyTypeConverter
     System.ServiceModel.Discovery.ConfigurationDiscoveryVersionConverter
     System.ServiceModel.XamlIntegrationEndpointIdentityConverter
     System.ServiceModel.XamlIntegrationServiceXNameTypeConverter
     System.ServiceModel.XamlIntegrationXPathMessageContextTypeConverter
     SystemUriTypeConverter
     System.Web.ConfigurationLowerCaseStringConverter
     System.Web.UI.DesignDataBindingCollectionConverter
     System.Web.UI.DesignDataColumnSelectionConverter
     System.Web.UI.DesignDataFieldConverter
     System.Web.UI.DesignDataMemberConverter
     System.Web.UI.DesignDataSourceConverter
     System.Web.UI.DesignDataSourceViewSchemaConverter
     System.Web.UI.DesignExpressionsCollectionConverter
     System.Web.UI.Design.MobileControls.ConvertersDataFieldConverter
     System.Web.UI.Design.MobileControls.ConvertersDataMemberConverter
     System.Web.UI.DesignSkinIDTypeConverter
     System.Web.UI.Design.WebControlsDataSourceIDConverter
     System.Web.UI.WebControlsFontNamesConverter
     System.Web.UI.WebControlsFontUnitConverter
     System.Web.UI.WebControlsStringArrayConverter
     System.Web.UI.WebControlsUnitConverter
     System.Windows.ControlsDataGridLengthConverter
     System.Windows.Controls.RibbonRibbonControlLengthConverter
     System.Windows.Controls.RibbonStringCollectionConverter
     System.Windows.ControlsVirtualizationCacheLengthConverter
     System.WindowsCornerRadiusConverter
     System.WindowsCultureInfoIetfLanguageTagConverter
     System.WindowsDeferrableContentConverter
     System.WindowsDialogResultConverter
     System.WindowsDurationConverter
     System.WindowsDynamicResourceExtensionConverter
     System.WindowsExpressionConverter
     System.WindowsFigureLengthConverter
     System.WindowsFontSizeConverter
     System.WindowsFontStretchConverter
     System.WindowsFontStyleConverter
     System.WindowsFontWeightConverter
     System.Windows.FormsAxHostStateConverter
     System.Windows.FormsCursorConverter
     System.Windows.FormsDataGridPreferredColumnWidthTypeConverter
     System.Windows.FormsDataGridViewCellStyleConverter
     System.Windows.FormsKeysConverter
     System.Windows.Forms.LayoutTableLayoutSettingsTypeConverter
     System.Windows.FormsLinkAreaLinkAreaConverter
     System.Windows.FormsLinkConverter
     System.Windows.FormsListBindingConverter
     System.Windows.FormsOpacityConverter
     System.Windows.FormsPaddingConverter
     System.Windows.FormsScrollableControlDockPaddingEdgesConverter
     System.Windows.FormsSelectionRangeConverter
     System.Windows.FormsTreeNodeConverter
     System.WindowsGridLengthConverter
     System.Windows.InputCommandConverter
     System.Windows.InputCursorConverter
     System.Windows.InputInputScopeConverter
     System.Windows.InputInputScopeNameConverter
     System.Windows.InputKeyConverter
     System.Windows.InputKeyGestureConverter
     System.Windows.InputModifierKeysConverter
     System.Windows.InputMouseActionConverter
     System.Windows.InputMouseGestureConverter
     System.WindowsInt32RectConverter
     System.WindowsKeySplineConverter
     System.WindowsKeyTimeConverter
     System.WindowsLengthConverter
     System.Windows.MarkupDependencyPropertyConverter
     System.Windows.MarkupEventSetterHandlerConverter
     System.Windows.MarkupNameReferenceConverter
     System.Windows.MarkupRoutedEventConverter
     System.Windows.MarkupSetterTriggerConditionValueConverter
     System.Windows.MarkupTemplateKeyConverter
     System.Windows.MarkupXmlLanguageConverter
     System.Windows.Media.AnimationRepeatBehaviorConverter
     System.Windows.MediaBrushConverter
     System.Windows.MediaCacheModeConverter
     System.Windows.MediaColorConverter
     System.Windows.Media.ConvertersBaseIListConverter
     System.Windows.MediaDoubleCollectionConverter
     System.Windows.MediaFontFamilyConverter
     System.Windows.MediaGeometryConverter
     System.Windows.MediaImageSourceConverter
     System.Windows.MediaInt32CollectionConverter
     System.Windows.MediaMatrixConverter
     System.Windows.Media.Media3DMatrix3DConverter
     System.Windows.Media.Media3DPoint3DCollectionConverter
     System.Windows.Media.Media3DPoint3DConverter
     System.Windows.Media.Media3DPoint4DConverter
     System.Windows.Media.Media3DQuaternionConverter
     System.Windows.Media.Media3DRect3DConverter
     System.Windows.Media.Media3DSize3DConverter
     System.Windows.Media.Media3DVector3DCollectionConverter
     System.Windows.Media.Media3DVector3DConverter
     System.Windows.MediaPathFigureCollectionConverter
     System.Windows.MediaPixelFormatConverter
     System.Windows.MediaPointCollectionConverter
     System.Windows.MediaRequestCachePolicyConverter
     System.Windows.MediaTransformConverter
     System.Windows.MediaVectorCollectionConverter
     System.WindowsPointConverter
     System.WindowsPropertyPathConverter
     System.WindowsRectConverter
     System.WindowsSizeConverter
     System.WindowsStrokeCollectionConverter
     System.WindowsTemplateBindingExpressionConverter
     System.WindowsTemplateBindingExtensionConverter
     System.WindowsTextDecorationCollectionConverter
     System.WindowsThicknessConverter
     System.WindowsVectorConverter
     System.Workflow.ComponentModel.DesignActivityBindTypeConverter
     System.Xaml.SchemaXamlTypeTypeConverter