c# - How does compiler know it needs to return an expression tree? -


is hard-coded compiler return expression tree when encounters lambda assigned expression <func<t>> following?

expression<func<int, int>> exp = n => n;

yes, in c# 5 specification document in section 4.6 "expression tree types"

4.6 expression tree types
expression trees permit lambda expressions represented data structures instead of executable code. expression trees values of expression tree types of form system.linq.expressions.expression<d>, d delegate type. remainder of specification refer these types using shorthand expression<d>. if conversion exists lambda expression delegate type d, conversion exists expression tree type expression<d>. whereas conversion of lambda expression delegate type generates delegate references executable code lambda expression, conversion expression tree type creates expression tree representation of lambda expression. expression trees efficient in-memory data representations of lambda expressionsand make structure of lambda expressiontransparent , explicit. delegate type d, expression<d> said have parameter , return types, same of d. following example represents lambda expressionboth executable code , expression tree. because conversion exists func<int,int>, conversion exists expression<func<int,int>>:

func<int,int> del = x => x + 1;                       // code expression<func<int,int>> exp = x => x + 1;       // data 

following these assignments, delegate del references method returns x + 1, , expression tree exp references data structure describes expression x => x + 1. exact definition of generic type expression precise rules constructing expression tree when lambda expressionis converted expression tree type, both outside scope of specification. 2 things important make explicit:

  • not lambda expressionscan converted expression trees. instance, lambda expressionswith statement bodies, , lambda expressionscontaining assignment expressions cannot represented. in these cases, conversion still exists, fail @ compile-time. these exceptions detailed in §6.5.
  • expression offers instance method compile produces delegate of type d:

    func<int,int> del2 = exp.compile();

invoking delegate causes code represented expression tree executed. thus, given definitions above, del , del2 equivalent, , following 2 statements have same effect:

int i1 = del(1); int i2 = del2(1); 

after executing code, i1 , i2 both have value 2.


Comments

Popular posts from this blog

c# - Update a combobox from a presenter (MVP) -

How to understand 2 main() functions after using uftrace to profile the C++ program? -

How to put a lock and transaction on table using spring 4 or above using jdbcTemplate and annotations like @Transactional? -