Skip to content

Instantly share code, notes, and snippets.

@kjeske
Last active March 14, 2016 16:54
Show Gist options
  • Save kjeske/5005040 to your computer and use it in GitHub Desktop.
Save kjeske/5005040 to your computer and use it in GitHub Desktop.
Safely get the property value from a source object. If the source object is null, then get the default value.
public static class ObjectExtensions
{
public static TReturn safe<T, TReturn>(this T testedObject, Func<T, TReturn> member, TReturn defaultValue = default(TReturn))
where T : class
{
return testedObject != null ? member(testedObject) : defaultValue;
}
}
// Usage example:
// var host = Request.safe(x => x.UrlReferrer).safe(x => x.Host);
// the code above is a shotrcut of:
// var host = Request != null ? (Request.UrlReferrer != null ? Request.UrlReferrer.Host : null) : null;
@kjeske
Copy link
Author

kjeske commented Feb 27, 2014

Usage example:
var host = Request.safe(x => x.UrlReferrer).safe(x => x.Host);

the code above is a shotrcut of:
var host = Request != null ? (Request.UrlReferrer != null ? Request.UrlReferrer.Host : null) : null;

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