ExtensionMethod.NET Home of 880 C#, Visual Basic, F# and Javascript extension methods

FormatIf

Conditionally formats any value type based on a Lambda Expression

Source

public static string FormatIf<T>(this T value, string format) where T : struct {
 return FormatIf(value, null, format, null);
}

public static string FormatIf<T>(this T value, string format, string defaultText) where T : struct {
 return FormatIf(value, null, format, defaultText);
}

public static string FormatIf<T>(this T value, Func<T, bool> condition, string format, string defaultText) where T : struct {
 if(condition == null) condition = v => v.IsNotEmpty();
 return (condition(value) ? string.Format(format, value) : defaultText);
}

Example

var dt = DateTime.Now;
Console.WriteLine(dt.FormatIf(d => d.Date != DateTime.Now.Date, "The selected day is {0:d}", "today"));

Author: Patrick A. Lorenz

Submitted on: 19 mrt. 2008

Language: C#

Type: System.ValueType

Views: 4422