Tony Johansson said:
I have hard to see a situation when I would use the reflection feature to
create the code dynamically ?
Can somebody give me a hint when this situation would arise ?
It's much much easier to create the code in the normal way.
Okay, I'll give you an example. Imagine the following challenge: You have
to write a program where the user types-in a function such as
"y=2*Cos(x)-1", and you have to paint an x-y graph showing that curve. Note
that the expression is entered by the user into a textbox. You do not know
it at compile time, so you cannot "create the code in the normal way", to
quote your own words.
To paint the graph, you would assign multiple values to x, and perform
the operations to get the valye of y. You would then plot the (x,y) points
into your output graphic.
So, you need to produce code that is able to evaluate quickly, hundreds
of times, a function that is entered by the user. How do you accomplish
this? The first way that comes to mind is to use the CSharpComiler class to
compile the expression, producing an assembly, and then invoke the method
inside the assembly by means of reflection. This works, but the compilation
process is not very fast (it uses a temporary file on disk) and it has the
drawback that the assembly remains loaded in memory after you are done using
it, so your program wil "leak" memory if you repeat the proccess many times
as the user types new expressions. Of course, you could load the assembly
into a different AppDomain and then unload it, but this would introduce
additional complexity, and you would need to use cross-domain calls to
evaluate the function.
So, what is another alternative? Write a syntax analyzer to analyze the
expression that the user typed, and then use Emit to produce some MSIL code
that is equivalent to the expression. You then execute this code. The code
is produced in memory (no temporary file), and the result is a DynamicMethod
that evaluates the function as needed. The DynamicMethod is subject to
garbage colection, so you will not leak memory if the process is repeated
multiple times.
If you want an example, you can take a look at an article the I wrote on
this subject. The text of the article is written in Spanish, but you can
copy and paste the C# code and it will work fine regardless of your language
. This is the URL:
http://www.scribd.com/doc/24018633/Como-crear-un-compilador-de-expresiones-en-NET