Skip to content

Instantly share code, notes, and snippets.

@duncansmart
Created April 4, 2011 09:08
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save duncansmart/901329 to your computer and use it in GitHub Desktop.
Save duncansmart/901329 to your computer and use it in GitHub Desktop.
Type-safe GetMethod: get a MethodInfo without a magic string
using System;
using System.Reflection;
using System.Linq.Expressions;
class ExpressionUtil
{
// Returns the MethodInfo of the given lambda. Use instead of Type.GetMethod("name", paramTypes).
public static MethodInfo GetMethod<T>(Expression<Action<T>> lambda)
{
var call = lambda.Body as MethodCallExpression;
if (call == null)
throw new ArgumentException("Expression body was expected to be a method call, but was '" + lambda.Body + "' (" + call.GetType() + ")");
return call.Method;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment