📜 ⬆️ ⬇️

Type Value Conversion in .NET

Introduction to the problem


It would seem that such a simple topic as value conversion (value conversion) is not worthy of an entire article. In C # there is a suitable operator "(T) value", there are types that implement it, and the topic on this can be considered closed. But in the 14 years since .NET, the developers of BCL and other programmers have come up with 4 more ways to convert value types.



Here is a list of them:

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

In addition to this, there are Nullable [T] , System.Enum meta-types, which have their own methods for converting value types.
')
And all this variety of methods did not have one convenient API to convert A → B, without thinking about how the developer implemented the possibility of this conversion.

Decision


The TypeConvert class in the System namespace (yes, I know it’s bad to litter other people's namespaces).

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

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

In the README file there is a description of other methods.

Installation


All this lies in one file , which can be taken to your project and in a convenient Nuget-package:

 Install-Package TypeConvert 

There are 2 classes in the load to the Nuget-package:

TypeActivator - creating type instances through a cached constructor,
HexConvert - convert bytes / numbers to a hexadecimal representation and vice versa.

Application


In the ConsoleApp.CommandLine project for binding the transmitted parameters of unknown type to the known parameters of the method.

In private projects to convert the configuration values ​​obtained from JSON to specific complex types (Uri, IpAddress, TimeSpan ...).

Links


» Project on githaba

Source: https://habr.com/ru/post/315352/


All Articles