See Also: MarshalAsAttribute Members
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 UnmanagedType.LPStr, a UnmanagedType.LPWStr, a UnmanagedType.LPTStr, or a UnmanagedType.BStr. By default, the common language runtime marshals a string parameter as a UnmanagedType.BStr to COM methods. You can apply the System.Runtime.InteropServices.MarshalAsAttribute attribute to an individual field or parameter to cause that particular string to be marshaled as a UnmanagedType.LPStr instead of a UnmanagedType.BStr. The [<topic://cpgrfTypeLibraryExporterTlbexpexe>] 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 UnmanagedType.LPStr to a platform invoke method or function. For additional information, see [<topic://cpcondefaultmarshalingbehavior>].
In most cases, the attribute simply identifies the format of the unmanaged data using the System.Runtime.InteropServices.UnmanagedType enumeration, as shown in the following C# signature:
Example
void MyMethod([MarshalAs(LPStr)] String s);
Some System.Runtime.InteropServices.UnmanagedType enumeration members require additional information. For example, additional information is needed when the System.Runtime.InteropServices.UnmanagedType is UnmanagedType.LPArray. For a complete description of how to use this attribute with arrays, see [<topic://cpcondefaultmarshalingforarrays>].
The [<topic://cpgrfTypeLibraryImporterTlbimpexe>] 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 System.Runtime.InteropServices.MarshalAsAttribute to string and object types for clarity, regardless of the type specified in the input type library.
The System.Runtime.InteropServices.MarshalAsAttribute does not support marshaling of generic types.