Skip to content
Martijn Bodeman edited this page Aug 20, 2023 · 33 revisions

The Iban type comes with TypeConverter support, allowing it the be converted to and from string.

  • When converting from string to Iban, validation occurs automatically.
  • When converting from Iban to string the value is formatted using the 'Electronic' format.

IbanTypeConverter

There may be cases where you do not have direct access to the parser, or you are building generic converters/serializers where you do not know the type (to convert) at compile time, or you are using other libraries/API's that are not extensible but they do support type conversion.

An example is the JSON support for the Iban type via JSON.NET/Newtonsoft, which is entirely relying on type conversion without IbanNet having to take a dependency on the Newtonsoft library.

Examples

From string type To Iban type:

Type type = typeof(Iban);
string strValue = "NL91 ABNA 0417 1643 00";

TypeConverter typeConverter = TypeDescriptor.GetConverter(type); // returns instance of IbanTypeConverter
object value = typeConverter.ConvertFromInvariantString(strValue); // returns Iban: NL91ABNA0417164300

From Iban type to string:

object value = ...; // a value of type Iban;

TypeConverter typeConverter = TypeDescriptor.GetConverter(value.GetType()); // returns instance of IbanTypeConverter
string strIban = typeConverter.ConvertToInvariantString(value);

Note: this produces effectively the same result as calling value.ToString() itself. It depends entirely on your use case.

Caveat

Unfortunately, most implementations that use type converters simply call ConvertFrom(Object) (including the examples listed above) as opposed to ConvertFrom(ITypeDescriptorContext,CultureInfo,Object). This means that an IIbanValidator cannot be resolved using the IServiceProvider provided by ITypeDescriptorContext since it will always return null. In such case, type conversion falls back to using the static Iban.Validator instance.

The good news is that the default behavior of IbanNet's IoC integration packages also set the static Iban.Validator instance and thus everything should still work (apart from exceptional use cases).

In previous versions of IbanNet, the static validator instance was used in several places by IbanNet. Since v4 its only use case is for type conversion, to be used as fallback validator when no validator instance can be resolved from an IoC container. It will have a default validator instance, but you can also set it to a custom configured validator instance.