Created
November 30, 2012 12:15
-
-
Save mikeeast/4175450 to your computer and use it in GitHub Desktop.
GetValueSafe extension method
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 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) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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