Some questions about the usage of MethodImpl Attribute

1.9k views Asked by At

The MSDN reference of the MethodImplOptions are these:

MethodImplOptions Enumeration


I would like to learn, firstly, in what circunstances I should use MethodImpl(MethodImplOptions.Unmanaged) and the most important thing, what are the beneffits/optimizations of this (if any)?

I suuposed that I should use it when I do a call to WinAPI function or to a function in a third party C/C++ library, then, this code-example is right?:

<MethodImpl(MethodImplOptions.Unmanaged)>
Public Shared Sub MyMethod()

    ' Call to
    SafeOrUnsafeNativeMethodsClass.RanodmWinAPIFunction()

End Sub

Secondlly, I would like to learn what value I should use for methods that are declared as shared in a Class, methods that could be call from any part of the code.

An example:

' Sealed class.
Public NotInheritable Class class1

    ' No instanceable class.    
    Private Sub New()
    End Sub

    Public Shared Function MyFunc(ByVal parameter1 As String) As Boolean

        Return A Boolean Value

    End Function

End Class

What value of the MethodImplOptions EnumerationI should set for that method in the MethodImpl attribute?.

Here is an user test that demonstrates inlining causes bad performance:

https://softwareengineering.stackexchange.com/questions/245802/is-there-a-downside-to-using-aggressiveinlining-on-simple-properties

Howhever, I'm not sure if inlining is what I should specify, of if I should set NoOptimization, or what value that will take best performance in the circunstances of shared methods.

1

There are 1 answers

0
IS4 On BEST ANSWER

MSDN:

Unmanaged The method is implemented in unmanaged code.

This means the method body is in unmanaged code, not that it will get compiled to it. This flag is used in C++/CLI assemblies.

I'd say don't use this attribute, the JIT should handle inlining by itself, when needed (as it is written in the article you posted).