Last active
July 21, 2017 17:50
-
-
Save jeremiahredekop/86b89831e65c7f305585 to your computer and use it in GitHub Desktop.
Piping c# extension methods
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//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()); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
why should fsharp get all the fun? These are the last extension methods you'll ever need.