Skip to content

Instantly share code, notes, and snippets.

@Tewr
Last active July 6, 2016 14:24
Show Gist options
  • Save Tewr/b7a6a491539c9db7f360c435b66193cc to your computer and use it in GitHub Desktop.
Save Tewr/b7a6a491539c9db7f360c435b66193cc to your computer and use it in GitHub Desktop.
Helper for classes decorated with DefaultValueAttribute
using System;
using System.ComponentModel;
using System.Linq.Expressions;
using System.Reflection;
namespace Extensions
{
public static class ComponentModelExtensions
{
public static TProperty GetPropertyValueOrDefault<TSource, TProperty>(
this TSource source,
Expression<Func<TSource, TProperty>> propertyLambda)
{
var propInfo = GetPropertyInfo(source, propertyLambda);
var instanceValue = propInfo.GetValue(source);
if (instanceValue == null || ((TProperty)instanceValue).Equals(default(TProperty)))
{
var defaultValueAttribute = propInfo.GetCustomAttribute<DefaultValueAttribute>()?.Value;
if (defaultValueAttribute != null)
return (TProperty) defaultValueAttribute;
}
return (TProperty)instanceValue;
}
private static PropertyInfo GetPropertyInfo<TSource, TProperty>(
TSource source,
Expression<Func<TSource, TProperty>> propertyLambda)
{
Type type = typeof(TSource);
MemberExpression member = propertyLambda.Body as MemberExpression;
if (member == null)
throw new ArgumentException(string.Format(
"Expression '{0}' refers to a method, not a property.",
propertyLambda.ToString()));
PropertyInfo propInfo = member.Member as PropertyInfo;
if (propInfo == null)
throw new ArgumentException(string.Format(
"Expression '{0}' refers to a field, not a property.",
propertyLambda.ToString()));
if (type != propInfo.ReflectedType &&
!type.IsSubclassOf(propInfo.ReflectedType))
throw new ArgumentException(string.Format(
"Expresion '{0}' refers to a property that is not from type {1}.",
propertyLambda.ToString(),
type));
return propInfo;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment