deniszykov.TypeConversion 3.1.0

.NET Core 2.1 .NET Standard 1.6 .NET Framework 4.5
dotnet add package deniszykov.TypeConversion --version 3.1.0
NuGet\Install-Package deniszykov.TypeConversion -Version 3.1.0
This command is intended to be used within the Package Manager Console in Visual Studio, as it uses the NuGet module's version of Install-Package.
<PackageReference Include="deniszykov.TypeConversion" Version="3.1.0" />
For projects that support PackageReference, copy this XML node into the project file to reference the package.
paket add deniszykov.TypeConversion --version 3.1.0
#r "nuget: deniszykov.TypeConversion, 3.1.0"
#r directive can be used in F# Interactive, C# scripting and .NET Interactive. Copy this into the interactive tool or source code of the script to reference the package.
// Install deniszykov.TypeConversion as a Cake Addin
#addin nuget:?package=deniszykov.TypeConversion&version=3.1.0

// Install deniszykov.TypeConversion as a Cake Tool
#tool nuget:?package=deniszykov.TypeConversion&version=3.1.0

dotnet_build

Introduction

For historical reasons, .NET has several approaches to value conversion:

  • Explicit/Implicit operators
  • System.Convert class
  • IConvertible interface
  • System.ComponentModel.TypeConverter
  • To, From, Parse, Create methods
  • Constructors (Uri, Guid)
  • Meta types (Enums, Nullable Types).

This package combines all these approaches under one API.

Installation

Install-Package deniszykov.TypeConversion 

Usage

TypeConversionProvider methods
// generic
ToType Convert<FromType, ToType>(fromValue, [format], [formatProvider]);
bool TryConvert<FromType, ToType>(fromValue, out result, [format], [formatProvider]);
string ConvertToString<FromType>(fromValue, [format], [formatProvider]);

// non-generic
object Convert(fromValue, toType, fromValue, [format], [formatProvider]);
bool TryConvert(fromValue, toType, fromValue, out result, [format], [formatProvider]);

Example

using deniszykov.TypeConversion;

  var conversionProvider = new TypeConversionProvider();
  var timeSpanString = "00:00:01";
  
  var timeSpan = conversionProvider.Convert<string, TimeSpan>(timeSpanString);
  
  // with default settings TimeSpan.Parse(value, format, formatProvider) 
  // is used for conversion inside Convert<string, TimeSpan>()

Configuration

using deniszykov.TypeConversion;

var configuration = new TypeConversionProviderConfiguration
{
  Options = ConversionOptions.UseDefaultFormatIfNotSpecified
};

#if NET45
var typeConversionProvider = new TypeConversionProvider(configuration);
#else
var typeConversionProvider = new TypeConversionProvider(Options.Create(configuration));
#endif

Or configure via DI

using deniszykov.TypeConversion;
using Microsoft.Extensions.DependencyInjection;

Host.CreateDefaultBuilder().ConfigureServices(IServiceCollection services) => {

  // add configuration
  services.Configure<TypeConversionProviderConfiguration>(options =>
  {
    options.DefaultFormatProvider = CultureInfo.CurrentUICulture;
  });

  // register service
  services.AddSingleton<ITypeConversionProvider, TypeConversionProvider>();
}

Which conversion method is used?

At the beginning, for each pair of types, all possible conversions are found. Then they are sorted by quality and the best one is selected. In one group, method with parameter type closest in inheritance to the required one is selected. For debug purposes TypeConversionProvider.DebugPrintConversions could be used to review which conversion methods are selected.

Quality of conversions form worst to best:

  • Constructor (worst)
  • System.ComponentModel.TypeConverter
  • Methods like Parse, From, To
  • Explicit conversion operator
  • Implicit conversion operator
  • Build-in (long → int, class → null)
  • Custom

Providing custom conversion between types

using deniszykov.TypeConversion;
using Microsoft.Extensions.DependencyInjection;

Host.CreateDefaultBuilder().ConfigureServices(IServiceCollection services) => {

    // register custom conversion from Uri to string
    serviceCollection.AddSingleton<ICustomConversionRegistration>(
        new CustomConversion<Uri, string>((uri, _, _) => uri.OriginalString)
    );

    // register custom conversion from string to Uri
    serviceCollection.AddSingleton<ICustomConversionRegistration>(
        new CustomConversion<string, Uri>((str, _, _) => new Uri(str))
    );
    
    // ...  
}

Preparing for AOT runtime

using deniszykov.TypeConversion;
using Microsoft.Extensions.DependencyInjection;

Host.CreateDefaultBuilder().ConfigureServices(IServiceCollection services) => {

  services.Configure<TypeConversionProviderConfiguration>(options =>
  {
    // disable optimizations which use dynamic code generation
    options.Options &= ~(ConversionOptions.OptimizeWithExpressions | ConversionOptions.OptimizeWithGenerics);
  });
  
}

Key Abstractions

interface ITypeConversionProvider; // provides methods to get IConverter
interface IConverter<FromType, ToType>; // converts values
interface IConversionMetadataProvider; // provides metadata for ITypeConversionProvider
Product Versions
.NET net5.0 net5.0-windows net6.0 net6.0-android net6.0-ios net6.0-maccatalyst net6.0-macos net6.0-tvos net6.0-windows net7.0 net7.0-android net7.0-ios net7.0-maccatalyst net7.0-macos net7.0-tvos net7.0-windows
.NET Core netcoreapp1.0 netcoreapp1.1 netcoreapp2.0 netcoreapp2.1 netcoreapp2.2 netcoreapp3.0 netcoreapp3.1
.NET Standard netstandard1.6 netstandard2.0 netstandard2.1
.NET Framework net45 net451 net452 net46 net461 net462 net463 net47 net471 net472 net48
MonoAndroid monoandroid
MonoMac monomac
MonoTouch monotouch
Tizen tizen30 tizen40 tizen60
Xamarin.iOS xamarinios
Xamarin.Mac xamarinmac
Xamarin.TVOS xamarintvos
Xamarin.WatchOS xamarinwatchos
Compatible target framework(s)
Additional computed target framework(s)
Learn more about Target Frameworks and .NET Standard.

NuGet packages (5)

Showing the top 5 NuGet packages that depend on deniszykov.TypeConversion:

Package Downloads
Pluto

Pluto is an application server

RoguelikeToolkit.Entities

Package Description

WebView2.DOM

C# DOM bindings to be used with WebView2

deniszykov.CommandLine

Command line parser and binder. Provides API for parsing and binding command line arguments to .NET methods.

SliccDB

A simple, one file graph database!

GitHub repositories

This package is not used by any popular GitHub repositories.

Version Downloads Last updated
3.1.0 0 1/29/2023
3.0.8 1,056 10/7/2022
3.0.6 2,106 4/6/2022
3.0.2 5,891 8/4/2021
3.0.1 1,725 2/26/2021
3.0.0 226 1/29/2021

# 3.0.7-3.0.8
feature: added fast execution path for TryConvert methods, any transition methods like nullable-to-any, any-to-nullable, nullable-to-nullable, downcast support TryConvert variant and wouldn't fallback to Convert method. This change increase performance TryConvert calls.
fix: changed error for "No conversion exists" from InvalidOperationException to FormatException so it would be handled by TryConvert try/catch clause. This could be breaking change if you made logic based on exception types.

# 3.0.6
refac: renamed TypeConversionProviderConfiguration to TypeConversionProviderOptions
refac: renamed ConversionMetadataProviderConfiguration into ConversionMetadataProviderOptions to conform .NET Core configuration conversion.
feature: added type promotion function for value with ConversionOptions.PromoteValueToActualType
fix: fixed TargetInvocationException instead of actual error is thrown when some conversion failed and OptimizeWithExpressions is disabled in config.

# 3.0.5
refac: removed extra constructor TypeConversionProvider to prevent DI constructor confusion.
fix: fixed null to any ref type conversion error.

# 3.0.4
refac: deprecated TypeConversionProviderConfiguration.RegisterConversion in favor of TypeConversionProvider constructor injection.
feature: added TypeConversionProviderConfiguration.DebugPrintConversions for debug purposes.

# 3.0.3
feature: added additional way to configure new conversions between types via constructor. This way allow service resolution for such conversions. Type need to be registered in DI ICustomConversionRegistration and services could be injected in implementation constructor.

# 3.0.2

fix: fixed usage of dynamic methods in EnumConversionInfo (frag was checked wrongly)
feature: added compatibility shim for old 'TypeConvert' package

# 3.0.0
- renamed project to `deniszykov.TypeConversion`
- removed HexConvert, Base64Convert, TypeActivator
- refactored TypeConvert to `ITypeConversionProvider` abstraction and `TypeConversionProvider` implementation
- added configurable behaviour via `TypeConversionProviderConfiguration` and `IConversionMetadataProvider`
- renamed `EnumHelper` to EnumConversionInfo and made it instantiable class instead of static class.