Skip to content

Instantly share code, notes, and snippets.

@bleroy
Created April 21, 2014 04:02
Show Gist options
  • Select an option

  • Save bleroy/11131888 to your computer and use it in GitHub Desktop.

Select an option

Save bleroy/11131888 to your computer and use it in GitHub Desktop.

Revisions

  1. bleroy created this gist Apr 21, 2014.
    29 changes: 29 additions & 0 deletions NotNull
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,29 @@
    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.");
    }
    properties.Add((PropertyInfo)memberExpression.Member);
    current = memberExpression.Expression;
    }
    properties.Reverse();
    object currentValue = source;
    foreach (var propertyInfo in properties) {
    if (currentValue == null) return default(TProp);
    currentValue = propertyInfo.GetValue(currentValue);
    }
    return (TProp) currentValue;
    }
    }
    }