Advertisement
hejmus

Untitled

Nov 2nd, 2012
59
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 0.85 KB | None | 0 0
  1. TR GetObjectProperty<T, TR>(T p, Expression<Func<T, TR>> action)
  2.         {
  3.             var expression = (MemberExpression)action.Body;
  4.             var name = expression.Member.Name;
  5.  
  6.             try
  7.             {
  8.                 return (TR)TypeDescriptor.GetProperties(p).Find(name, true).GetValue(p);
  9.             }
  10.             catch
  11.             {
  12.                 return (TR)GetDefault(TypeDescriptor.GetProperties(p).Find(name, true).PropertyType);
  13.             }
  14.         }
  15.  
  16.         public object GetDefault(Type t)
  17.         {
  18.             return this.GetType().GetMethod("GetDefaultGeneric").MakeGenericMethod(t).Invoke(this, null);
  19.         }
  20.         public T GetDefaultGeneric<T>()
  21.         {
  22.             if (typeof(T).IsValueType)
  23.                 return default(T);
  24.             else
  25.                 return Activator.CreateInstance<T>();
  26.         }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement