<commit_before>[![Build Status](https://travis-ci.org/deniszykov/typeconvert.svg?branch=master)](https://travis-ci.org/deniszykov/typeconvert)

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).

TypeConvert combines all these approaches under one API. 
Additionally this package has hexadecimal conversion API and type instancing API(cached for better perfomance).
Each utility class in this package can be used separately and you are free to embedd them into your project.

#### TypeConvert
```csharp
// generic
ToType Convert<FromType, ToType>(value, [format], [formatProvider]);
bool TryConvert<FromType, ToType>(value, out result, [format], [formatProvider])
string ToString<FromType>(value, [format], [formatProvider]);
// non-generic
object Convert(value, toType, [format], [formatProvider]);
bool TryConvert(ref value, toType, [format], [formatProvider]);
string ToString(value, [format], [formatProvider]);
```

#### TypeActivator
```csharp
object CreateInstance(type, forceCreate = false);
object CreateInstance<Arg1T, ...>(type, arg1 ...);
```

#### HexConvert
```csharp
string ToString(buffer, offset, count); // bytes -> hex
byte[] ToBytes(hexString, offset, count); // hex -> bytes

void Encode(buffer, offset, count, hexBuffer, hexBufferOffset); // bytes chunk -> hex chunk
void Decode(hexBuffer, offset, count, buffer, bufferOffset); // hex chunk -> bytes chunk

int WriteTo(number, hexBuffer, offset); // number -> hex
Number ToNumber(hexBuffer, offset) // hex -> number
```

Installation
============
```
Install-Package TypeConvert 
```

Examples
========
## TypeConvert
Convert from string to integer
```csharp
TypeConvert.Convert<string, int>("1") // 1
```	
Convert from integer to Enum
```csharp
TypeConvert.Convert<int, ConsoleColor>(1) // DarkBlue
```	
Convert from string to IPAddress
```csharp
TypeConvert.Convert<string, IPAddress>("127.0.0.1") // 127.0.0.1 via IPAddress.Parse
```
Convert to string with format(if supported)
```csharp
TypeConvert.ToString(1000000, format: "x") // f4240
```	
Convert from any to IpAddress
```csharp
TypeConvert.Convert("127.0.0.1", typeof(IPAddress)); 127.0.0.1 via IPAddress.Parse
```
Testing conversion
```csharp
TypeConvert.TryConvert<string, int>("xxx", out intValue) // false
```
## TypeActivator
Creating from default constructor
```csharp
TypeActivator.CreateInstance(typeof(int)); // 0
```
Getting class instance without default constructor
```csharp
TypeActivator.CreateInstance(typeof(EventArgs)); // via EventArgs.Empty
```
Getting class instance without default constructor and Empty property
```csharp
TypeActivator.CreateInstance(typeof(IPEndPoint), force: true); // IPEndPoint bypassing constructor
```
Creating an array
```csharp
TypeActivator.CreateInstance(typeof(int[])); // int[0] (same instance every time)
```<commit_msg>docs: updated README to match current state of project<commit_after>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
```csharp
// generic
ToType ITypeConversionProvider.Convert<FromType, ToType>(fromValue, [format], [formatProvider]);
bool ITypeConversionProvider.TryConvert<FromType, ToType>(fromValue, out result, [format], [formatProvider])
string ITypeConversionProvider.ConvertToString<FromType>(fromValue, [format], [formatProvider]);
// non-generic
object ITypeConversionProvider.Convert(fromValue, toType, fromValue, [format], [formatProvider]);
bool ITypeConversionProvider.TryConvert(fromValue, toType, fromValue, out result, [format], [formatProvider]);
```

## Example
```csharp
  var conversionProvider = new TypeConversionProvider();
  var timeSpanString = "00:00:01";
  var timeSpan = conversionProvider.Convert<object, TimeSpan>(timeSpanString);
```

## Configuration
```csharp
  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
```csharp
.ConfigureServices(IServiceCollection services) => {
  services.Configure<TypeConversionProviderConfiguration>(options =>
  {
    options.DefaultFormatProvider = CultureInfo.CurrentUICulture;
  });
  // services.AddSingleton<IConversionMetadataProvider, MyCustomConversionMetadataProvider>();
  services.AddSingleton<ITypeConversionProvider, TypeConversionProvider>();
}
```

### Providing custom conversion between types
```csharp
.ConfigureServices(IServiceCollection services) => {
  services.Configure<TypeConversionProviderConfiguration>(options =>
  {
    options.RegisterConversion<Uri, string>((uri, format, formatProvider) => uri.OriginalString);
  });
}
```

### Preparing for AOT runtime
```csharp
.ConfigureServices(IServiceCollection services) => {
  services.Configure<TypeConversionProviderConfiguration>(options =>
  {
	// disable optimizations which use dynamic code generation
    options.Options &= ~(ConversionOptions.OptimizeWithExpressions | ConversionOptions.OptimizeWithGenerics);
  });
}
```

## Key Abstractions

```csharp
interface ITypeConversionProvider // provides methods to get IConverter
interface IConverter<FromType, ToType> // converts values
interface IConversionMetadataProvider // provides metadata for ITypeConversionProvider
```


{'fraction_non_alphanumeric': 0.13113940797089466, 'fraction_numerical': 0.00826856292376385, 'mean_word_length': 6.411764705882353, 'pattern_counts': {'":': 0, '<': 22, '<?xml version=': 0, '>': 35, 'https://': 2, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 4, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '2383638', 'n_tokens_mistral': 1732, 'n_tokens_neox': 1628, 'n_words': 458}