.maxstack
is part of the IL verification. Basically .maxstack
tells the JIT the max stack size it needs to reserve for the method. For example, x = y + (a - b)
translates to
(Pseudo IL:)
1. Push y on the stack
2. Push a on the stack
3. Push b on the stack
4. Pop the last two items from the stack,
substract them and
push the result on the stack
5. Pop the last two items from the stack,
add them and
push the result on the stack
6. Store the last item on the stack in x and
pop the last item from the stack
As you can see, there are at most 3 items on the stack at each time.
If you'd set .maxstack
to 2 (or less) for this method, the code wouldn't run.
Also, you cannot have something like this as it would require an infinite stack size:
1. Push x on the stack
2. Jump to step 1
To answer your questions:
- does this apply just for the function, or to all the functions that we are calling for?
Just for the function
- even if it's just for the function were .maxstack is being declared, how do you know what maxstack is if you have branching? You go and see all the "paths" and return the maximum value possible?
You go and see all the paths and return the maximum value possible
- What happens if I set it to 16 and actually there are 17 variables?
It's unrelated to the number of variables, see Lasse V. Karlsen's answer
- Is there a too big of a penalty if I set it to 256?
Doesn't seem like a good idea, but I don't know.
Do you really have to calculate the .maxstack
yourself? System.Reflection.Emit
calculates it for you IIRC.