Skip to content

Instantly share code, notes, and snippets.

@joelverhagen
Last active August 29, 2015 14:12
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save joelverhagen/085fd29fdfd7d0bd5102 to your computer and use it in GitHub Desktop.
Save joelverhagen/085fd29fdfd7d0bd5102 to your computer and use it in GitHub Desktop.
Convert a Try... function in C# to a Get... function.
// 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);
}
}
}
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