What is inlining?
What is it used for?
Can you inline something in C#?
What is inlining?
What is it used for?
Can you inline something in C#?
What it is
In the terms of C and C++ you use the inline keyword to tell the compiler to call a routine without the overhead of pushing parameters onto the stack. The Function instead has it's machine code inserted into the function where it was called. This can create a significant increase in performance in certain scenarios.
Dangers
The speed benefits in using "inlining" decrease significantly as the size of the inline function increases. Overuse can actually cause a program to run slower. Inlining a very small accessor function will usually decrease code size while inlining a very large function can dramatically increase code size.
Inlining in C#
In C# inlining happens at the JIT level in which the JIT compiler makes the decision. There is currently no mechanism in C# which you can explicitly do this. If you wish to know what the JIT compiler is doing then you can call: System.Reflection.MethodBase.GetCurrentMethod().Name
at runtime. If the Method is inlined it will return the name of the caller instead.
In C# you cannot force a method to inline but you can force a method not to. If you really need access to a specific callstack and you need to remove inlining you can use: MethodImplAttribute
with MethodImplOptions.NoInlining
. In addition if a method is declared as virtual then it will also not be inlined by the JIT. The reason behind this is that the final target of the call is unknown.
More on inlining
For definition and discussion of inlining, see this question.
In C# you don't need to instruct the compiler or run-time to inline because the run-time will do it automatically.
P.S. This answer is also correct for Java.
Inlining is when instead of calling a particular function, the contents of the function are done directly at the call site. The main reason for doing this is that it removes the overhead of calling a function by running the function contents at the callsite.
It is used as an optimization technique. In the case of C#, it actually depends on the CLR JIT engine to do the work. At runtime, when compiling a method, the JIT engine will use a heuristic to determine if a function inline is appropriate and will be an effictive optimization. If so, an inline is performed.
Vance has a great article on what the JIT considers when inlining: http://blogs.msdn.com/vancem/archive/2008/08/19/to-inline-or-not-to-inline-that-is-the-question.aspx
There is no way to force an inline in C#. The language does not support this construct. Mainly because people are very poor judges of what should be optimized. The JITer is a much better judge.
To quote Eric Gunnerson
inlining happens at the JIT level, and the JIT generally makes a decent decision