Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save matt-hensley/f3ae5fed23a90876d3359e57d293a350 to your computer and use it in GitHub Desktop.
Save matt-hensley/f3ae5fed23a90876d3359e57d293a350 to your computer and use it in GitHub Desktop.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;
namespace DapperSample {
public static class StaticReflection {
public static string GetMemberName<T>(
this T instance,
Expression<Func<T, object>> expression) {
return GetMemberName(expression);
}
public static string GetMemberName<T>(
Expression<Func<T, object>> expression) {
if (expression == null) {
throw new ArgumentException(
"The expression cannot be null.");
}
return GetMemberName(expression.Body);
}
public static string GetMemberName<T, TValue>(
Expression<Func<T, TValue>> expression) {
if (expression == null) {
throw new ArgumentException(
"The expression cannot be null.");
}
return GetMemberName(expression.Body);
}
public static string GetMemberName<T>(
this T instance,
Expression<Action<T>> expression) {
return GetMemberName(expression);
}
public static string GetMemberName<T>(
Expression<Action<T>> expression) {
if (expression == null) {
throw new ArgumentException(
"The expression cannot be null.");
}
return GetMemberName(expression.Body);
}
private static string GetMemberName(
Expression expression) {
if (expression == null) {
throw new ArgumentException(
"The expression cannot be null.");
}
if (expression is MemberExpression) {
// Reference type property or field
var memberExpression =
(MemberExpression)expression;
return memberExpression.Member.Name;
}
if (expression is MethodCallExpression) {
// Reference type method
var methodCallExpression =
(MethodCallExpression)expression;
return methodCallExpression.Method.Name;
}
if (expression is UnaryExpression) {
// Property, field of method returning value type
var unaryExpression = (UnaryExpression)expression;
return GetMemberName(unaryExpression);
}
throw new ArgumentException("Invalid expression");
}
private static string GetMemberName(
UnaryExpression unaryExpression) {
if (unaryExpression.Operand is MethodCallExpression) {
var methodExpression =
(MethodCallExpression)unaryExpression.Operand;
return methodExpression.Method.Name;
}
return ((MemberExpression)unaryExpression.Operand)
.Member.Name;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment