Last active
August 29, 2015 14:12
-
-
Save joelverhagen/085fd29fdfd7d0bd5102 to your computer and use it in GitHub Desktop.
Convert a Try... function in C# to a Get... function.
This file contains 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
// Try it out: http://ideone.com/Aubx5H | |
using System; | |
namespace Knapcode.KitchenSink.Extensions | |
{ | |
public static class UniversalExtensions | |
{ | |
public delegate bool TryGetValue<in TInput, TOutput>(TInput input, out TOutput value); | |
public static TOutput GetTryValue<TInput, TOutput>(this TInput input, TryGetValue<TInput, TOutput> tryGetValue) | |
{ | |
TOutput value; | |
if (!tryGetValue(input, out value)) | |
{ | |
value = default(TOutput); | |
} | |
return value; | |
} | |
} | |
public class Program | |
{ | |
public static void Main() | |
{ | |
const string number = "42"; | |
Console.WriteLine(number.GetTryValue<string, int>(int.TryParse) + 23); | |
} | |
} | |
} |
This file contains 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
namespace Knapcode.KitchenSink.Extensions | |
{ | |
public static class UniversalExtensions | |
{ | |
public delegate bool TryGetValue<in TInput, TOutput>(TInput input, out TOutput value); | |
public static TOutput GetTryValue<TInput, TOutput>(this TInput input, TryGetValue<TInput, TOutput> tryGetValue) | |
{ | |
TOutput value; | |
if (!tryGetValue(input, out value)) | |
{ | |
value = default(TOutput); | |
} | |
return value; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment