Skip to content

Instantly share code, notes, and snippets.

@mikeeast
Created November 30, 2012 12:15
Show Gist options
  • Save mikeeast/4175450 to your computer and use it in GitHub Desktop.
Save mikeeast/4175450 to your computer and use it in GitHub Desktop.
GetValueSafe extension method
public static TResult GetValueSafe<TInstance, TResult>(this TInstance instance, Func<TInstance, TResult> accessor, TResult defaultValue = default(TResult))
where TInstance : class
{
return instance != null ? accessor(instance) : defaultValue;
}
usage:
someNullableObject.GetValueSafe(p => p.SomeProperty)
or
someNullableObject.GetValueSafe(p => p.SomeProperty, string.Empty)
@mausch
Copy link

mausch commented Nov 30, 2012

You might want to take a look at the Maybe monad, which generalizes that and adds many other operations, while also being safer since it wraps the value in an explicit option type. Some examples in https://github.com/fsharp/fsharpx/blob/master/tests/FSharpx.CSharpTests/OptionTests.cs

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