crozone / FormatWith

String extensions for named parameterized string formatting.
MIT License
73 stars 13 forks source link

Add Support for generic value dictionaries #25

Closed timjen3 closed 3 years ago

timjen3 commented 3 years ago

Would be nice if the library supported dictionaries with generic types.

var inputs = new Dictionary<string, double>
{
    { "a", 1 },
    { "b", 2 }
};
var result = "{a},{b}".FormatWith(inputs, MissingKeyBehaviour.ThrowException);
// throws System.Collections.Generic.KeyNotFoundException
timjen3 commented 3 years ago

Since an IDictionary<string, double> can't be passed as an IDictionary<string, object> it is using the object extension method which is not working as desired with dictionaries.

If you convert the dictionary it will work. (Note: you can't cast)

var inputs = new Dictionary<string, double>
{
    { "a", 1 },
    { "b", 2 }
};
var inputs2 = new Dictionary<string, object>();
foreach (var item in inputs)
    inputs2[item.Key] = item;
var result = "{a},{b}".FormatWith(inputs2, MissingKeyBehaviour.ThrowException);
// expected behavior

Are there better ways to do this conversion so the extension methods work?

My suggestion is to add extension methods with type parameters, ex:

public static string FormatWith<TValue>(this string formatString, IDictionary<string, TValue> replacements);
crozone commented 3 years ago

Great idea with the generic overload. I'll roll it in with the IReadOnlyDictionary change in the 4.0 release.

crozone commented 3 years ago

Implemented in commit 6dc381ed2fc7ced0ac3100f096cf1ca081e08431, will be included in 4.0 release.

timjen3 commented 3 years ago

Excellent. I like this library over SmartFormat because it's light weight and has a more explicit API. I appreciate your dedication to continuous improvement! Kudos.

crozone commented 3 years ago

Closing this since it's implemented on 4.0 and I want the little milestone graph to go up.