deniszykov.TypeConversion
3.2.3
dotnet add package deniszykov.TypeConversion --version 3.2.3
NuGet\Install-Package deniszykov.TypeConversion -Version 3.2.3
<PackageReference Include="deniszykov.TypeConversion" Version="3.2.3" />
paket add deniszykov.TypeConversion --version 3.2.3
#r "nuget: deniszykov.TypeConversion, 3.2.3"
// Install deniszykov.TypeConversion as a Cake Addin #addin nuget:?package=deniszykov.TypeConversion&version=3.2.3 // Install deniszykov.TypeConversion as a Cake Tool #tool nuget:?package=deniszykov.TypeConversion&version=3.2.3
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 Compatible and additional computed target framework versions. |
---|---|
.NET | net5.0 was computed. net5.0-windows was computed. net6.0 was computed. net6.0-android was computed. net6.0-ios was computed. net6.0-maccatalyst was computed. net6.0-macos was computed. net6.0-tvos was computed. net6.0-windows was computed. net7.0 is compatible. net7.0-android was computed. net7.0-ios was computed. net7.0-maccatalyst was computed. net7.0-macos was computed. net7.0-tvos was computed. net7.0-windows was computed. net8.0 was computed. net8.0-android was computed. net8.0-browser was computed. net8.0-ios was computed. net8.0-maccatalyst was computed. net8.0-macos was computed. net8.0-tvos was computed. net8.0-windows was computed. |
.NET Core | netcoreapp1.0 was computed. netcoreapp1.1 was computed. netcoreapp2.0 was computed. netcoreapp2.1 is compatible. netcoreapp2.2 was computed. netcoreapp3.0 was computed. netcoreapp3.1 was computed. |
.NET Standard | netstandard1.6 is compatible. netstandard2.0 was computed. netstandard2.1 is compatible. |
.NET Framework | net45 is compatible. net451 was computed. net452 was computed. net46 was computed. net461 is compatible. net462 was computed. net463 was computed. net47 was computed. net471 was computed. net472 was computed. net48 was computed. net481 was computed. |
MonoAndroid | monoandroid was computed. |
MonoMac | monomac was computed. |
MonoTouch | monotouch was computed. |
Tizen | tizen30 was computed. tizen40 was computed. tizen60 was computed. |
Xamarin.iOS | xamarinios was computed. |
Xamarin.Mac | xamarinmac was computed. |
Xamarin.TVOS | xamarintvos was computed. |
Xamarin.WatchOS | xamarinwatchos was computed. |
-
.NETCoreApp 2.1
- Microsoft.Extensions.Options (>= 3.1.10)
-
.NETFramework 4.5
- No dependencies.
-
.NETFramework 4.6.1
- Microsoft.Extensions.Options (>= 5.0.0)
-
.NETStandard 1.6
- Microsoft.Extensions.Options (>= 1.1.2)
- NETStandard.Library (>= 1.6.1)
- System.Runtime.Serialization.Primitives (>= 4.3.0)
-
.NETStandard 2.1
- Microsoft.Extensions.Options (>= 3.1.10)
-
net7.0
- Microsoft.Extensions.Options (>= 3.1.10)
NuGet packages (5)
Showing the top 5 NuGet packages that depend on deniszykov.TypeConversion:
Package | Downloads |
---|---|
Pluto
Pluto is an application server |
|
deniszykov.CommandLine
Command line parser and binder. Provides API for parsing and binding command line arguments to .NET methods. |
|
RoguelikeToolkit.Entities
Package Description |
|
WebView2.DOM
C# DOM bindings to be used with WebView2 |
|
SliccDB
A simple, one file graph database! |
GitHub repositories (1)
Showing the top 1 popular GitHub repositories that depend on deniszykov.TypeConversion:
Repository | Stars |
---|---|
pmikstacki/SliccDB
Light Embedded Graph Database for .net
|
# 3.2.2 - 3.2.3
fix: fixed ParameterInfo.GetCustomAttributes throws IndexOutOfRangeException for Linux https://github.com/mono/mono/issues/17192
# 3.2.1
fix: changed AOT implementation of EnumConversion to use direct unboxing of numeric values into/from Enum values. This is kinda hacky, but gives better perfomance.
feature: allow to register safe conversion functions (like TryParse, TryConvert, TryCreate) with `CustomConversion{T1,T2}` or via `ICustomConversionRegistry.RegisterConversion`
# 3.1.1
feature: added support for TryParse/TryCreate methods. These methods would be called directly from `IConverter.TryConvert` and also fallback option for `IConverter.Convert`. This will increase performance of `IConverter.TryConvert`.
feature: added `Options.DisallowedMethodNames` to exclude "Exact" methods from conversion methods due their tendency to fail without proper format
fix: fixed method ranging to make sure more specific method (with format and formatProvider parameters) used first.
# 3.0.9
fix: fixed NullConverter preventing from using Nullable fallback conversions and obscuring other conversion ways. Also it throws raw System.Exception.
# 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.