All Projects → deniszykov → TypeConversion

deniszykov / TypeConversion

Licence: MIT license
C# library which provides uniform API for conversion between types.

Programming Languages

C#
18002 projects

Projects that are alternatives of or similar to TypeConversion

coers
A small library for coercion to primitive Erlang types.
Stars: ✭ 23 (+35.29%)
Mutual labels:  conversion, coercion
placekey-py
placekey.io
Stars: ✭ 49 (+188.24%)
Mutual labels:  conversion
Svg2pdf.js
A javascript-only SVG to PDF conversion utility that runs in the browser. Brought to you by yWorks - the diagramming experts
Stars: ✭ 231 (+1258.82%)
Mutual labels:  conversion
caffe weight converter
Caffe-to-Keras weight converter. Can also export weights as Numpy arrays for further processing.
Stars: ✭ 68 (+300%)
Mutual labels:  conversion
Rink Rs
Unit conversion tool and library written in rust
Stars: ✭ 242 (+1323.53%)
Mutual labels:  conversion
shell2batch
Coverts simple basic shell scripts to windows batch scripts.
Stars: ✭ 42 (+147.06%)
Mutual labels:  conversion
Kepubify
Fast, standalone EPUB to KEPUB converter CLI app / library (and a few other utilities).
Stars: ✭ 225 (+1223.53%)
Mutual labels:  conversion
OpenConvert
Text conversion tool (from e.g. Word, HTML, txt) to corpus formats TEI or FoLiA)
Stars: ✭ 20 (+17.65%)
Mutual labels:  conversion
roffit
converts nroff man pages to HTML
Stars: ✭ 84 (+394.12%)
Mutual labels:  conversion
units
A run-time C++ library for working with units of measurement and conversions between them and with string representations of units and measurements
Stars: ✭ 114 (+570.59%)
Mutual labels:  conversion
bank2ynab
Easily convert and import your bank's statements into YNAB. This project consolidates other conversion efforts into one universal tool.
Stars: ✭ 197 (+1058.82%)
Mutual labels:  conversion
Decaffeinate
Goodbye CoffeeScript, hello JavaScript!
Stars: ✭ 2,658 (+15535.29%)
Mutual labels:  conversion
sms
A Go library for encoding and decoding SMSs
Stars: ✭ 37 (+117.65%)
Mutual labels:  conversion
Dimensioned
Compile-time dimensional analysis for various unit systems using Rust's type system.
Stars: ✭ 235 (+1282.35%)
Mutual labels:  conversion
BlocksConverter
A PocketMine-MP plugin allows you to convert Minecraft PC maps to MCPE/Bedrock maps or vice-versa.
Stars: ✭ 47 (+176.47%)
Mutual labels:  conversion
Gotenberg
A Docker-powered stateless API for PDF files.
Stars: ✭ 3,272 (+19147.06%)
Mutual labels:  conversion
fp-units
An FP-oriented library to easily convert CSS units.
Stars: ✭ 18 (+5.88%)
Mutual labels:  conversion
cvs2gitdump
python scripts which import cvs tree into git or subversion repository
Stars: ✭ 18 (+5.88%)
Mutual labels:  conversion
biguint-format
Node.js module to format big uint numbers from a byte array or a Buffer
Stars: ✭ 16 (-5.88%)
Mutual labels:  conversion
embedded-time
Time(ing) library (Instant/Duration/Clock/Timer/Period/Frequency) for bare-metal embedded systems
Stars: ✭ 72 (+323.53%)
Mutual labels:  conversion

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
Note that the project description data, including the texts, logos, images, and/or trademarks, for each open source project belongs to its rightful owner. If you wish to add or remove any projects, please contact us at [email protected].