Skip to content

Instantly share code, notes, and snippets.

@jeremiahredekop
Last active July 21, 2017 17:50
Show Gist options
  • Save jeremiahredekop/86b89831e65c7f305585 to your computer and use it in GitHub Desktop.
Save jeremiahredekop/86b89831e65c7f305585 to your computer and use it in GitHub Desktop.
Piping c# extension methods
public static class PipingExtensions
{
/// <summary>
/// Take an object, pipe it into a function, and return the result.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <typeparam name="T2"></typeparam>
/// <param name="obj"></param>
/// <param name="f"></param>
/// <returns></returns>
public static T2 Pipe<T, T2>(this T obj, Func<T, T2> f)
{
return f(obj);
}
/// <summary>
/// Pipes object it into a function, and returns object.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="obj"></param>
/// <param name="f"></param>
/// <remarks>useful for encapsulating procedural void method calls</remarks>
public static T PipeKeep<T>(this T obj, Action<T> f)
{
f(obj);
return obj;
}
/// <summary>
/// Pipes object into a void function (action)
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="obj"></param>
/// <param name="f"></param>
/// <remarks>for cases where the output is to be ignored</remarks>
public static void PipeVoid<T>(this T obj, Action<T> f)
{
f(obj);
}
}
//Adapter production usage which parses an NLog log level input and returns a custom enum
private static CustomLogLevel GetCustomLevel(LogLevel input)
{
return input.ToString()
.Pipe(str => Enum.Parse(typeof (SdLogLevel), str))
.Pipe(o => (CustomLogLevel) o);
// OR:
//return (CustomLogLevel) Enum.Parse(typeof(CustomLogLevel), input.ToString());
}
@jeremiahredekop
Copy link
Author

why should fsharp get all the fun? These are the last extension methods you'll ever need.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment