Dynamic methods in .NET Framework-supported languages
Dynamic methods, a feature of .NET Framework since v2.0, provide a way to create a method at program run time. When I learned about this feature, it looked like an opportunity for me to learn more about the intermediate language (IL) that is at the heart of .NET Framework programming.
By way of background, a program written in one of the languages supported by the .NET Framework is compiled into Microsoft Intermediate Language (MSIL). When the program is executed, the Common Language Runtime (CLR) has a just-in-time (or JIT) compiler that translates the IL codes into native machine instructions.
The program in the attached file has two dynamic methods. The first method has two int parameters, and returns the average of the two input values. The body of this method is six bytes! The second method converts a temperature from Celsius to Fahrenheit or vice versa. This method also has two parameters--one is the temperature, and the other is a Boolean flag that indicates whether the first parameter is a Celsius temperature or a Fahrenheit one. This body of this method is 36 bytes.
Both methods use integer division, so the results they produce aren't as precise as it would be using floating point division. Inasmuch as the goal for me was to use dynamic methods, precision was not a top priority.
Although the methods are tiny in size, there's a fair amount of overhead associated with using dynamic methods. You also need to include additional information about each method, namely maximum stack size during the method's execution, the method calling convention, the number of parameters, the type of each parameter, and the type of the return value.
The attached code file is extensively commented, to help you understand what's happening along the way. I have also included algorithms for each of the dynamic methods, as well as their IL opcodes.
You need to be logged in to comment