MarshalAsAttribute Class

Indicates how to marshal the data between managed and unmanaged code.

System.Object
  System.Attribute
    System.Runtime.InteropServices.MarshalAsAttribute

Namespace:  System.Runtime.InteropServices
Assemblies:   System.Runtime.InteropServices (in System.Runtime.InteropServices.dll)
  mscorlib (in mscorlib.dll)

[AttributeUsageAttribute(AttributeTargets.Field|AttributeTargets.Parameter|AttributeTargets.ReturnValue, Inherited = false)]
public sealed class MarshalAsAttribute : Attribute

The MarshalAsAttribute type exposes the following members.

  NameDescription
Public methodSupported by the XNA FrameworkSupported by Portable Class LibrarySupported in .NET for Windows Store appsMarshalAsAttribute(Int16)Initializes a new instance of the MarshalAsAttribute class with the specified UnmanagedType value.
Public methodSupported by the XNA FrameworkSupported by Portable Class LibrarySupported in .NET for Windows Store appsMarshalAsAttribute(UnmanagedType)Initializes a new instance of the MarshalAsAttribute class with the specified UnmanagedType enumeration member.
Top

  NameDescription
Public propertyTypeIdWhen implemented in a derived class, gets a unique identifier for this Attribute. (Inherited from Attribute.)
Public propertySupported by the XNA FrameworkSupported by Portable Class LibrarySupported in .NET for Windows Store appsValueGets the UnmanagedType value the data is to be marshaled as.
Top

  NameDescription
Public methodSupported by the XNA FrameworkSupported by Portable Class LibrarySupported in .NET for Windows Store appsEqualsInfrastructure. Returns a value that indicates whether this instance is equal to a specified object. (Inherited from Attribute.)
Public methodSupported by the XNA FrameworkSupported by Portable Class LibrarySupported in .NET for Windows Store appsGetHashCodeReturns the hash code for this instance. (Inherited from Attribute.)
Public methodSupported by the XNA FrameworkSupported by Portable Class LibrarySupported in .NET for Windows Store appsGetTypeGets the Type of the current instance. (Inherited from Object.)
Public methodIsDefaultAttributeWhen overridden in a derived class, indicates whether the value of this instance is the default value for the derived class. (Inherited from Attribute.)
Public methodSupported by the XNA FrameworkMatchWhen overridden in a derived class, returns a value that indicates whether this instance equals a specified object. (Inherited from Attribute.)
Public methodSupported by the XNA FrameworkSupported by Portable Class LibrarySupported in .NET for Windows Store appsToStringReturns a string that represents the current object. (Inherited from Object.)
Top

  NameDescription
Public fieldSupported by the XNA FrameworkSupported by Portable Class LibrarySupported in .NET for Windows Store appsArraySubTypeSpecifies the element type of the unmanaged UnmanagedType.LPArray or UnmanagedType.ByValArray.
Public fieldSupported by Portable Class LibrarySupported in .NET for Windows Store appsIidParameterIndexSpecifies the parameter index of the unmanaged iid_is attribute used by COM.
Public fieldSupported by Portable Class LibrarySupported in .NET for Windows Store appsMarshalCookieProvides additional information to a custom marshaler.
Public fieldSupported by Portable Class LibrarySupported in .NET for Windows Store appsMarshalTypeSpecifies the fully qualified name of a custom marshaler.
Public fieldSupported by Portable Class LibrarySupported in .NET for Windows Store appsMarshalTypeRefImplements MarshalAsAttribute.MarshalType as a type.
Public fieldSupported by Portable Class LibrarySupported in .NET for Windows Store appsSafeArraySubTypeIndicates the element type of the UnmanagedType.SafeArray.
Public fieldSupported by Portable Class LibrarySupported in .NET for Windows Store appsSafeArrayUserDefinedSubTypeIndicates the user-defined element type of the UnmanagedType.SafeArray.
Public fieldSupported by the XNA FrameworkSupported by Portable Class LibrarySupported in .NET for Windows Store appsSizeConstIndicates the number of elements in the fixed-length array or the number of characters (not bytes) in a string to import.
Public fieldSupported by the XNA FrameworkSupported by Portable Class LibrarySupported in .NET for Windows Store appsSizeParamIndexIndicates the zero-based parameter that contains the count of array elements, similar to size_is in COM.
Top

  NameDescription
Explicit interface implemetationPrivate method_Attribute.GetIDsOfNamesMaps a set of names to a corresponding set of dispatch identifiers. (Inherited from Attribute.)
Explicit interface implemetationPrivate method_Attribute.GetTypeInfoRetrieves the type information for an object, which can be used to get the type information for an interface. (Inherited from Attribute.)
Explicit interface implemetationPrivate method_Attribute.GetTypeInfoCountRetrieves the number of type information interfaces that an object provides (either 0 or 1). (Inherited from Attribute.)
Explicit interface implemetationPrivate method_Attribute.InvokeProvides access to properties and methods exposed by an object. (Inherited from Attribute.)
Top

You can apply this attribute to parameters, fields, or return values.

This attribute is optional, as each data type has a default marshaling behavior. This attribute is only necessary when a given type can be marshaled to multiple types. For example, you can marshal a string to unmanaged code as either a LPStr, a LPWStr, a LPTStr, or a BStr. By default, the common language runtime marshals a string parameter as a BStr to COM methods. You can apply the MarshalAsAttribute attribute to an individual field or parameter to cause that particular string to be marshaled as a LPStr instead of a BStr. The Tlbexp.exe (Type Library Exporter) passes your marshaling preferences to the common language runtime.

Some parameters and return values have different default marshaling behavior when used with COM interop or platform invoke. By default, the runtime marshals a string parameter (and fields in a value type) as a LPStr to a platform invoke method or function. For additional information, see Default Marshaling Behavior.

In most cases, the attribute simply identifies the format of the unmanaged data using the UnmanagedType enumeration, as shown in the following C# signature:

void
    MyMethod([MarshalAs(LPStr)] String s);

Some UnmanagedType enumeration members require additional information. For example, additional information is needed when the UnmanagedType is LPArray. For a complete description of how to use this attribute with arrays, see Default Marshaling for Arrays.

The Tlbimp.exe (Type Library Importer) also applies this attribute to parameters, fields, and return values to indicate that the data type in the input type library is not the default type for the corresponding managed data type. Tlbimp.exe always applies the MarshalAsAttribute to String and Object types for clarity, regardless of the type specified in the input type library.

NoteNote

The MarshalAsAttribute does not support marshaling of generic types.

The following examples show the placement of the MarshalAsAttribute in managed source code as applied to parameters, field, and return values.

using System;
using System.Text;
using System.Runtime.InteropServices;


class Program
{

//Applied to a parameter. 
  public void M1([MarshalAs(UnmanagedType.LPWStr)]String msg) {}


//Applied to a field within a class. 
  class MsgText {
                [MarshalAs(UnmanagedType.LPWStr)]
                public String msg = "Hello World";
                }

//Applied to a return value.
[return: MarshalAs(UnmanagedType.LPWStr)]
    public String GetMessage()
    {
        return "Hello World";
    }


static void Main(string[] args)
    {  }
}

The following Visual Basic example demonstrates how to apply the MarshalAsAttribute attribute to properties:

Public Property Money () As <MarshalAs(UnmanagedType.Currency)> Decimal
        Get
            Return Me._money
        End Get
        Set(<MarshalAs(UnmanagedType.Currency)> ByVal value As Decimal)
            Me._money = value
        End Set
End Property
Private _money As Decimal

The equivalent C# code is shown in the following example:

public decimal Money { 
    [return: MarshalAs(UnmanagedType.Currency)]
    get {
        return this.money;
    }
    [param: MarshalAs(UnmanagedType.Currency)]
    set {
        this.money = value;
    }
}

.NET Framework

Supported in: 4.5.3, 4, 3.5, 3.0, 2.0, 1.1, 1.0

.NET Framework Client Profile

Supported in: 4, 3.5 SP1

Portable Class Library

Supported in: Portable Class Library

.NET for Windows Store apps

Supported in: Windows 8

Supported in: Windows Phone 8.1

Supported in: Windows Phone Silverlight 8.1

Supported in: Windows Phone Silverlight 8

Windows Phone 8.1, Windows Phone 8, Windows 8.1, Windows Server 2012 R2, Windows 8, Windows Server 2012, Windows 7, Windows Vista SP2, Windows Server 2008 (Server Core Role not supported), Windows Server 2008 R2 (Server Core Role supported with SP1 or later; Itanium not supported)

The .NET Framework does not support all versions of every platform. For a list of the supported versions, see .NET Framework System Requirements.

Any public static (Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe.
Was this page helpful?
(1500 characters remaining)
Thank you for your feedback
Show:
© 2014 Microsoft