Skip to content
Create a gist now

Instantly share code, notes, and snippets.

Embed URL


Subversion checkout URL

You can clone with
Download ZIP
using System;
using System.Collections.Generic;
using System.Linq.Expressions;
using System.Reflection;
namespace Bleroy.Helpers {
public static class NotNull {
public static TProp Get<TSource, TProp>(this TSource source, Expression<Func<TSource, TProp>> property) where TSource : class {
if (source == null) return default(TProp);
var current = property.Body;
var properties = new List<PropertyInfo>();
while (!(current is ParameterExpression)) {
var memberExpression = current as MemberExpression;
if (memberExpression == null || !(memberExpression.Member is PropertyInfo)) {
throw new InvalidOperationException("All members in the expression must be properties.");
current = memberExpression.Expression;
object currentValue = source;
foreach (var propertyInfo in properties) {
if (currentValue == null) return default(TProp);
currentValue = propertyInfo.GetValue(currentValue);
return (TProp) currentValue;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Something went wrong with that request. Please try again.