One of the things that frustrated me when I first started learning how to write (and rewrite) IL back in the early 2000’s was the fact that there were very few practical examples on how to do anything useful with IL. In fact, the only reliable learning tools that were available around at the time was PEVerify.exe, and IL disassembler. In the six to seven years since I first started writing/rewriting IL, I often asked myself what it would take to write a useful IL tutorial that would be easy enough for someone with a minimal C# background to learn, and yet be informative enough that it would be useful to someone who has written an AOP framework of their own.
Fast forward to 2011
Over the years, I have learned some really hard lessons about IL, and now that I’ll be speaking
at NDC 2011, it will be the first time that I will get to share what I have learned with the .NET community. Make no mistake—IL writing can
be a “mystery wrapped
in frustration containing an enigma”, but the good news is that I have been through many of those pitfalls, and now I can help other developers understand
what’s going on when those errors occur, and I can even show you how to fix those errors.
Ten Lessons Learned
In fact, there are ten basic principles that you can follow that will make it easier for you to understand and work with IL writing/rewriting. These principles are:
- Rule #1: If you don’t understand IL, then learn from the C# compiler
- Rule #2: Always keep the stack in a balanced state; One push = one pop
- Rule #3: Don’t forget to explicitly box/unbox your types
- Rule #4: PEVerify.exe can be your best friend and worst enemy at the same time
- Rule #5: Use Console.WriteLine() to triangulate errors in your IL at runtime; Use it well, and use it often
- Rule #6: GOTO statements in IL are a Good Thing™
- Rule #7: Emit as few IL instructions as possible
- Rule #8: Almost anything can be modified, including sealed classes and final methods
- Rule #9: You can replace any given method call as long as you replace it with a method that leaves the stack in the same state
- Rule #10: IL can be learned like any other programming language; practice makes perfect.
Many of these lessons learned are fairly straightforward, while some principles will require a bit more explanation during the talk. No matter what your level of experience
in IL might be, I guarantee that this is one informative session that you won’t want to miss. Stay tuned, and I’ll see you all at NDC 2011!