Skip to content

Instantly share code, notes, and snippets.

@AlexArchive
Created September 3, 2014 15:23
Show Gist options
  • Save AlexArchive/82ddfc3c7516a98a1679 to your computer and use it in GitHub Desktop.
Save AlexArchive/82ddfc3c7516a98a1679 to your computer and use it in GitHub Desktop.
Impress your friends with your terse and expressive reflection code.

Before:

public static class Calculator
{
    public static int Add(
        int numberOne, 
        int numberTwo, 
        int numberThree, 
        int numberFour, 
        int numberFive)
    {
        return numberOne + 
               numberTwo + 
               numberThree + 
               numberFour + 
               numberFive;
    }
}
...

MethodInfo boo =
    typeof(Calculator).GetMethod("Add", new[]
    {
        typeof(int), 
        typeof(int), 
        typeof(int), 
        typeof(int), 
        typeof(int)
    });

After:

public static class Calculator
{
    public static int Add(
        int numberOne, 
        int numberTwo, 
        int numberThree, 
        int numberFour, 
        int numberFive)
    {
        return numberOne + 
               numberTwo + 
               numberThree + 
               numberFour + 
               numberFive;
    }
}
...

MethodInfo actual =
    Reflect.Method(() => Calculator.Add(0, 0, 0, 0, 0));
public static class Reflect
{
public static MethodInfo Method<T>(Expression<Func<T>> expression)
{
return (MethodInfo) MethodImplementation(expression);
}
public static MethodInfo Method(Expression<Action> expression)
{
return (MethodInfo) MethodImplementation(expression);
}
public static PropertyInfo Property<T>(Expression<Func<T>> expression)
{
return (PropertyInfo) MethodImplementation(expression);
}
public static ConstructorInfo Constructor<T>(Expression<Func<T>> expression)
{
return (ConstructorInfo) MethodImplementation(expression);
}
public static FieldInfo Field<T>(Expression<Func<T>> expression)
{
return (FieldInfo) MethodImplementation(expression);
}
private static MemberInfo MethodImplementation(LambdaExpression expression)
{
if (expression.Body.NodeType == ExpressionType.Call)
return ((MethodCallExpression) expression.Body).Method;
if (expression.Body.NodeType == ExpressionType.MemberAccess)
return ((MemberExpression) expression.Body).Member;
if (expression.Body.NodeType == ExpressionType.New)
return ((NewExpression) expression.Body).Constructor;
throw new NotImplementedException();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment