[Note: The InAttribute and OutAttribute are not required. In the absence of explicit settings, the system assumes that all arguments passed by reference are passed in/out and that all non-reference parameters are in. The only exception is the System.Text.StringBuilder class, which is always assumed to be in/out. The InAttribute and OutAttribute are particularly useful when applied to formatted types that cannot be block-copied. Since these types require copying during marshaling, you can use InAttribute and OutAttribute to eliminate the generation of unnecessary copies.]

Compilers are required to not preserve this type in metadata as a custom attribute. Instead, compilers are required to emit it directly in the file format, as described in Partition II of the CLI Specification. Metadata consumers, such as the Reflection API, are required to retrieve this data from the file format and return it as if it were a custom attribute.

using System;

using System.Runtime.InteropServices;

using System.Text;

/// <summary>

/// Sample demonstrating the use of the OutAttribute class.

/// Use this class to indicate how parameters should be marshalled to unmanaged

/// code.

/// </summary>

internal class OutAttributeSample


    private static void Main()


        StringBuilder guidString = new StringBuilder(39).Append('\0', 39);

        Guid          newGuid    = Guid.NewGuid();

        if (StringFromGUID2(ref newGuid, guidString, guidString.Length) != 0)


            Console.WriteLine("Generated GUID: {0}", guidString);




            Console.WriteLine("StringFromGUID2 failed.");




        Console.WriteLine("Press Enter to continue");



    // Win32 method to convert a given GUID to a string. Note that the default

    // marshalling for StringBuilder is [in,out], so [Out] is used to override

    // the normal marshalling. This is used purely to demonstrate using the

    // OutAttribute; .NET code should use Guid.ToString() to perform the same

    // conversion.

    [DllImport("ole32.dll", CharSet=CharSet.Unicode)]

    private static extern int StringFromGUID2(

        [In]ref Guid rguid, [Out]StringBuilder lpsz, int cchMax);


The output is

Generated GUID: {36ED812C-BB9E-4154-B6F6-D8903F81738F}

Press Enter to continue

     Python   SQL   Java   php   Perl 
     game development   web development   internet   *nix   graphics   hardware 
     telecommunications   C++ 
     Flash   Active Directory   Windows