IProvider
IProvider is an interface for key-to-value providers. (Namespace Avalanche.Utilities.Provider)
/// <summary></summary>
public interface IProvider
{
/// <summary>Key type</summary>
Type Key { get; }
/// <summary>Value type</summary>
Type Value { get; }
/// <summary>Get value that corresponds <paramref name="key"/></summary>
/// <exception cref="InvalidCastException">If key is wrong type.</exception>
bool TryGetValue(object key, out object value);
}
IProvider<Key, Value> is for strong generics typed providers.
/// <summary></summary>
public interface IProvider<Key> : IProvider { }
/// <summary></summary>
public interface IProviderOf<Value> : IProvider { }
/// <summary></summary>
public interface IProvider<Key, Value> : IProvider<Key>, IProviderOf<Value>
{
/// <summary>Key to value indexer</summary>
/// <exception cref="KeyNotFoundException">If <paramref name="key"/> is not found.</exception>
Value this[Key key] { get; }
/// <summary>Try get <typeparamref name="Value"/> that corresponds <paramref name="key"/></summary>
bool TryGetValue(Key key, out Value value);
}
Provider can be used with indexer. If input is not found KeyNotFoundException is thrown.
// Create provider
IProvider<double, double> squareProvider = Providers.Func<double, double>(d => d * d);
// Use with indexer[value]
WriteLine(squareProvider[10.0]); // -> "100"
.TryGetValue(input, out output) tries to get a value. It doesn't throw errors on expected failure cases. The line between expected and unexpected failures is stated in the contract of the implementing class.
// Create provider
IProvider<double, double> squareProvider = Providers.Func<double, double>(d => d * d);
// Try Get value
if (squareProvider.TryGetValue(10.0, out double squared))
WriteLine(squared); // -> "100"
IProvider operates with object input and output.
// Create provider
IProvider squareProvider = Providers.Func<double, double>(d => d * d);
//
object input = 10.0;
// Try Get value
if (squareProvider.TryGetValue(input, out object squaredObject))
WriteLine(squaredObject); // -> "100"
Full Example
Full example
using Avalanche.Utilities.Provider;
using static System.Console;
class provider_index
{
public static void Run()
{
{
// <01>
// Create provider
IProvider<double, double> squareProvider = Providers.Func<double, double>(d => d * d);
// Use with indexer[value]
WriteLine(squareProvider[10.0]); // -> "100"
// </01>
}
{
// <02>
// Create provider
IProvider<double, double> squareProvider = Providers.Func<double, double>(d => d * d);
// Try Get value
if (squareProvider.TryGetValue(10.0, out double squared))
WriteLine(squared); // -> "100"
// </02>
}
{
// <03>
// Create provider
IProvider squareProvider = Providers.Func<double, double>(d => d * d);
//
object input = 10.0;
// Try Get value
if (squareProvider.TryGetValue(input, out object squaredObject))
WriteLine(squaredObject); // -> "100"
// </03>
}
}
}