using System.Reflection;
namespace System.Linq.Expressions
{
public static class ExpressionExtensions
{
///
/// Gets the full name (namespace, type name, method name, return type and argument types) of an instance method
/// called in an expression.
///
/// The type of the method's object.
/// An expression with a call to the method.
public static string GetMethodFullName(this Expression> expression) =>
expression.GetInvokedMethodInfo().GetFullName();
///
/// Gets the full name (namespace, type name, method name) of an instance method called in an expression.
///
/// The type of the method's object.
/// An expression with a call to the method.
public static string GetMethodSimpleName(this Expression> expression)
{
var methodInfo = expression.GetInvokedMethodInfo();
return methodInfo.DeclaringType.FullName + "." + methodInfo.Name;
}
private static MethodInfo GetInvokedMethodInfo(this Expression> expression)
{
// Since we need a specific method (i.e. if there are multiple overloads of it, then still one of them)
// this can't be simpler than requiring an expression.
var methodCallExpression = expression.Body as MethodCallExpression;
if (methodCallExpression == null)
{
throw new InvalidOperationException("The supplied expression is not a method call.");
}
return methodCallExpression.Method;
}
}
}