Search code examples
.netoperator-overloadingimplicittypeconverter

Are implicit operators and TypeConverters equivalent?


It seems to me its very easy to implement an implicit operator versus a TypeConverter, so I'm assuming they aren't equivalent because of the prevalence of TypeConverters in the framework (see anything that extends FrameworkElement).

But why? Wouldn't it have been much easier to create string->object and object->string implicit operators and take advantage of those in serialization (both XML and XAML)?

Is it YAGNI? Single responsibility? Because you can't specify operator overloads in interfaces?


Solution

  • Type converters are a lot more complex than they seem; a type-converter has access to a range of meta-data about the context of the conversion - for example, the property and object that are involved. This is used to provide custom options per scenario (think: linked drop-downs, i.e. Country / County / City / etc). You can also specify the type-converter on a per-property basis, which I use in lots of places to provide different handling of various string properties. An operator would treat all strings identically.

    An implicit operator only knows about the value that is being converted, but has far greater compile-time support.

    Or another way: TypeConverter is a framework feature with framework support; operators are (primarily) a language feature with language support

    To add more - type-converters (despite the name) don't just convert:

    • they provide sub-property metadata (think: expanding properties on PropertyGrid)
    • they suggest available options for a type (think: drop-down choices on PropertyGrid)

    Note they are used in more places than just PropertyGrid, though ;-p