Is there any reason not to push it out to a seperate method and then decorate that method with MethodImplOptions.AggressiveInlining ("The method should be inlined if possible").
As long as the method meets certain requirements (see below), the compiler will make a copy of the method at the point where it's called.
This would let you use Return
and tidy up your code considerably while also skipping the stack pushes, jumps, etc. usually associated with a method call.
Unfortunately, with the constraints you've imposed, there aren't many alternatives.
As requested, some example usage in VB.Net:
Imports System.Runtime.CompilerServices
<MethodImpl(MethodImplOptions.AggressiveInlining)>
Public Function Blah() As String
...
End Function
and C#
using System.Runtime.CompilerServices;
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public string Blah() {
...
}
I should mention that this is a hint to the compiler, and there are limits. The following don't support inlining;
- Virtual methods
- Recursive methods
- Methods that take a large value type as a parameter
- Methods on MarshalByRef classes
- Methods with complicated flowgraphs
- Methods meeting other, more exotic criteria
There may also be an IL byte count limit (There's a limit of 32 bytes without this flag, which is either increased or removed entirely). I haven't been able to find adequate documentation.