Created
July 2, 2014 11:40
-
-
Save OzieWest/b1f6d8fa1553f0734061 to your computer and use it in GitHub Desktop.
On accessing chains of potentially null properties
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
| using System; | |
| using System.Collections.Generic; | |
| using System.Linq.Expressions; | |
| using System.Reflection; | |
| namespace 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; | |
| } | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment