CA1403: Auto layout types should not be COM visible
Applies to: Visual Studio Visual Studio for Mac
Note
This article applies to Visual Studio 2017. If you're looking for the latest Visual Studio documentation, see Visual Studio documentation. We recommend upgrading to the latest version of Visual Studio. Download it here
Item | Value |
---|---|
RuleId | CA1403 |
Category | Microsoft.Interoperability |
Breaking change | Breaking |
Cause
A Component Object Model (COM) visible value type is marked with the System.Runtime.InteropServices.StructLayoutAttribute attribute set to System.Runtime.InteropServices.LayoutKind.Auto.
Rule description
LayoutKind layout types are managed by the common language runtime. The layout of these types can change between versions of .NET, which breaks COM clients that expect a specific layout. If the StructLayoutAttribute attribute is not specified, the C#, Visual Basic, and C++ compilers specify LayoutKind.Auto for value types.
Unless marked otherwise, all public, non-generic types are visible to COM, and all non-public and generic types are invisible to COM. However, to reduce false positives, this rule requires the COM visibility of the type to be explicitly stated. The containing assembly must be marked with the System.Runtime.InteropServices.ComVisibleAttribute set to false
and the type must be marked with the ComVisibleAttribute set to true
.
How to fix violations
To fix a violation of this rule, change the value of the StructLayoutAttribute attribute to LayoutKind.Explicit or LayoutKind.Sequential, or make the type invisible to COM.
When to suppress warnings
Do not suppress a warning from this rule.
Example
The following example shows a type that violates the rule and a type that satisfies the rule.
using System;
using System.Runtime.InteropServices;
[assembly: ComVisible(false)]
namespace InteroperabilityLibrary
{
// This violates the rule.
[StructLayout(LayoutKind.Auto)]
[ComVisible(true)]
public struct AutoLayout
{
public int ValueOne;
public int ValueTwo;
}
// This satisfies the rule.
[StructLayout(LayoutKind.Explicit)]
[ComVisible(true)]
public struct ExplicitLayout
{
[FieldOffset(0)]
public int ValueOne;
[FieldOffset(4)]
public int ValueTwo;
}
}
Imports System
Imports System.Runtime.InteropServices
<Assembly: ComVisibleAttribute(False)>
Namespace InteroperabilityLibrary
' This violates the rule.
<StructLayoutAttribute(LayoutKind.Auto)> _
<ComVisibleAttribute(True)> _
Public Structure AutoLayout
Dim ValueOne As Integer
Dim ValueTwo As Integer
End Structure
' This satisfies the rule.
<StructLayoutAttribute(LayoutKind.Explicit)> _
<ComVisibleAttribute(True)> _
Public Structure ExplicitLayout
<FieldOffsetAttribute(0)> _
Dim ValueOne As Integer
<FieldOffsetAttribute(4)> _
Dim ValueTwo As Integer
End Structure
End Namespace
Related rules
CA1408: Do not use AutoDual ClassInterfaceType