Written by 09:56 ASP .NET CORE, Languages & Coding

Type Conversion in .NET

Introduction

Such a simple topic as type conversion would seem to be unworthy of the whole article. In C#, there is a suitable operator “(T)value” and types that implement it. So, this topic may be considered as closed. However, for 14 years of .NET existence, BCL developers and other programmers have come up with other four ways to convert value types.

The list of types is as follows:

  1. System.Convert class;
  2. IConvertible interface;
  3. System.ComponentModel.TypeConverter;
  4. To, From, Parse, Create methods.

In addition, there are meta types Nullable[T] and System.Enum with their methods of type conversion.

All this variety of methods had one suitable API to convert A to В without thinking about the way a developer implemented the possibility of such conversion.

Solution

The TypeConvert class in the System namespace (I know that it is bad to clog other namespaces)

ToType Convert<FromType, ToType>(FromType value, string format, IFormatProvider formatProvider)

сonverts a value type from FromType to ToType, optionally using a format and formatting settings formatProvider. If there are no suitable methods that accept the settings, the option without formatting will be called.

The README file contains the description of other methods.

Installation

All this data can be found in one file, which you can take to your project in a compact Nuget package:

Install-Package TypeConvert

There are 2 classes along with Nuget-package:

TypeActivator is used to create instances of the type using a cached constructor,

HexConvert is used to convert bytes/numbers in hexadecimal representation and vice versa.

Application

It is possible to use it for binding passed parameters of an unknown type to known parameters of the method in the ConsoleApp.CommandLine project.

In private projects, the method can be used to convert values of configuration received from JSON to particular complicated types (Uri, IpAddress, TimeSpan…).

References:

Project on GitHub

Tags: , Last modified: September 23, 2021
Close