Table of Contents

ConvertibleConverterDictionary Class

Definition

Namespace
Cuemon
Assemblies
Cuemon.Kernel.dll
Source
src/Cuemon.Kernel/ConvertibleConverterDictionary.cs

Represents a collection of converters that map IConvertible implementations to byte arrays.

public class ConvertibleConverterDictionary : IReadOnlyDictionary<Type, Func<IConvertible, byte[]>>, IReadOnlyCollection<KeyValuePair<Type, Func<IConvertible, byte[]>>>, IEnumerable<KeyValuePair<Type, Func<IConvertible, byte[]>>>, IEnumerable
Inheritance
ConvertibleConverterDictionary
Implements

Examples

The following example demonstrates how to use to register and use type-specific converters that transform values into byte arrays.

// Program.cs
using System;
using System.Text;
using Cuemon;

var converters = new ConvertibleConverterDictionary()
    .Add<int>(value => BitConverter.GetBytes(value))
    .Add<long>(value => BitConverter.GetBytes(value))
    .Add<string>(value => Encoding.UTF8.GetBytes(value))
    .Add<bool>(value => BitConverter.GetBytes(value));

Console.WriteLine(converters.Count);

Console.WriteLine(converters.ContainsKey(typeof(int)));
Console.WriteLine(converters.ContainsKey(typeof(float)));

if (converters.TryGetValue(typeof(string), out var stringConverter))
{
    byte[] bytes = stringConverter("Hello");
    Console.WriteLine(bytes.Length);
    Console.WriteLine(Encoding.UTF8.GetString(bytes));
}

var intConverter = converters[typeof(int)];
if (intConverter != null)
{
    byte[] intBytes = intConverter(42);
    Console.WriteLine(BitConverter.ToInt32(intBytes));
}

foreach (var kvp in converters)
{
    Console.WriteLine($"{kvp.Key.Name} -> converter registered");
}

converters.Add(typeof(double), value => BitConverter.GetBytes(value.ToDouble(null)));
Console.WriteLine(converters.Count);
Console.WriteLine(converters.ContainsKey(typeof(double)));

Properties

Name Description
Count

Gets the number of converters contained in this instance.

this[Type]

Gets the converter associated with the specified type.

Keys

Gets the collection of types for which converters are registered.

Values

Gets the collection of registered converters.

Methods

Name Description
Add(Type, Func<IConvertible, byte[]>)

Adds a converter for the specified type.

Add<T>(Func<T, byte[]>)

Adds a converter for the specified T.

ContainsKey(Type)

Determines whether this dictionary contains a converter for the specified key.

GetEnumerator()

Returns an enumerator that iterates through the registered converters.

TryGetValue(Type, out Func<IConvertible, byte[]>)

Gets the converter associated with the specified key.