When I compile an expression into executable code and get the delegate – does the code get garbage collected when no more references to this delegate exist?
Is there any documentation on this? Because I didn’t find anything useful in the MSDN.
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
Yes, the code can be garbage collected. When you call Compile on an Expression of T, the code is compiled into a DynamicMethod, and those are eligible for garbage collection.
Indeed it’s not indicated on the MSDN, but you can have a look at the implementation of Expression<T>.Compile in the DLR, which is what .net 4.0 ships:
http://dlr.codeplex.com/SourceControl/changeset/view/54115#990638
Although the implementation of the compiler was different in .net 3.5, DynamicMethods were still used (source: myself, I implemented System.Linq.Expressions in Mono).
The case where compiled expression trees are not collectible, is when you use Expression<T>CompileToMethod, and that you pass a MethodBuilder from an AssemblyBuilder which was not created with the RunAndCollect flag.