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)

с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:

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

Denis Zykov

Denis Zykov

Denis Zykov has been developing on .NET since 2005. From 2005 to 2013 he was involved in the development of business software. In 2013 he switched to gamedev on back-end development. Denis Zykov participates in the open-source community, takes on the project and contributes to several open projects.
Denis Zykov

Latest posts by Denis Zykov (see all)

Denis Zykov

Denis Zykov has been developing on .NET since 2005. From 2005 to 2013 he was involved in the development of business software. In 2013 he switched to gamedev on back-end development. Denis Zykov participates in the open-source community, takes on the project and contributes to several open projects.