1

How I can get a custom attribute from a Function object?

public static void Main(string[] args) {

    Func<object> fun = () => Foo();

    //fun. Get Foo Custom Attribute
}

[CustomAttrib]
public static object Foo() {
    return new object();
}
Glorfindel
  • 21,988
  • 13
  • 81
  • 109
  • Or [this](http://stackoverflow.com/questions/3467765/get-method-details-using-reflection-and-decorated-attribute) – Yuval Itzchakov Jul 11 '15 at 10:56
  • The duplicate is incorrect - this is considerably more difficult because the method is inside a `Function`. – Glorfindel Jul 11 '15 at 11:10
  • 1
    Do you need to do this without actually calling the delegate and inspecting the retrieved object? – Lasse V. Karlsen Jul 11 '15 at 12:14
  • I would change the code to take a factory object through an interface instead of a `Func`. The factory interface should have a method for returning a new instance of the object, and a method for returning metadata/information about the type of object it can produce, make it part of the compiler-checked contract that you have all the pieces. A function or expression is going to be brittle, a mere if-statement inside will throw off any code you write from working. – Lasse V. Karlsen Jul 11 '15 at 12:28

1 Answers1

2

With a Function, the information you're looking for is not available AFAIK.

However, if it were an Expression, it would be quite easy:

Expression<Func<object>> expression = () => Foo();
var method = ((MethodCallExpression)expression.Body).Method;
Console.WriteLine(method.GetCustomAttributes(false)[0]);

You can convert an Expression to a Function with the Compile() method.

var fun = expression.Compile();

This might be helpful if you define the Function yourself, but not if comes from some 3rd party code which you can't modify.

Glorfindel
  • 21,988
  • 13
  • 81
  • 109
  • My advice would be to dispense with the function altogether and go for a more concrete interface that declares everything. Though using an expression instead of a delegate makes it much easier to inspect the code in the expression it is still going to be very hard to take "all expressions" and be able to handle them. A simple if-statement returning two different object types is going to throw a spanner in this. – Lasse V. Karlsen Jul 11 '15 at 12:29