andywilsonuk / StringTokenFormatter

Provides string extension methods for replacing tokens within strings (using the format '{name}') with their specified lookup value.
Apache License 2.0
37 stars 1 forks source link

Question: format a property that has a null value? #40

Closed rjperes closed 4 months ago

rjperes commented 4 months ago

How can I add a custom formatter that will be executed for a null property? I would like to replace all/some of my null properties with something like "N/A", is this at all possible? Thanks!

andywilsonuk commented 4 months ago

Hi. Yeah you can do that with a Value Converter.

Easiest way is to add it as the first converter within the settings, something like:

static TryGetResult NullConverter(object? value, string tokenName) => value is null ? TryGetResult.Success("N/A") : default;
var converters = (new TokenValueConverter[] { NullConverter }).Concat(StringTokenFormatterSettings.Default.ValueConverters).ToList();

var customSettings = StringTokenFormatterSettings.Default with {
    ValueConverters = converters
};
rjperes commented 4 months ago

Thanks a lot, @andywilsonuk! You saved my day! :-)