Posted by: Cirilo Meggiolaro | 01/21/2009

Tip of the day #99 – MethodImpl attribute

MethodImpl attribute is a pseudo-attribute. Just to give a quick overview, a pseudo-attribute is not saved in the metadata files as regular attributes but is used to set bits or fields within the metadata.

The purpose of the MethodImpl attribute is to specify how a method is implemented. To make it clear, let’s check the options available under the MethodImplOptions enumerator:

  • Unmanaged: Specifies that the method is implemented in unmanaged code;
  • NoInlining: Specifies that the method is not inlined by the JIT;
  • ForwardRef: Specifies that the method is declared only but implemented in a different place;
  • Synchronized: Has the same behavior than a lock to the whole method indicating that only one thread at a time is allowed to access the method;
  • NoOptimization: Specifies that the method is not optimized by the JIT or NGen;
  • PreserveSig: Preserve the method signature exporting it exactly as declared;
  • InternalCall: Specifies that the call is done to a method implemented within the CLR.

How to…

As any other attribute, apply the MethodImpl is pretty straightforward:

[MethodImpl(MethodImplOptions.NoInlining)]
public void MyMethodNotInlined()
{
    /// Some code.
}

[MethodImpl(MethodImplOptions.Synchronized)]
public void MySynchronizedMethod()
{
    /// Some code executed by one thread at a time.
}

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Categories

%d bloggers like this: