Export (0) Print
Expand All

CA1403: Auto layout types should not be COM visible







Breaking Change


A Component Object Model (COM) visible value type is marked with the System.Runtime.InteropServices.StructLayoutAttribute attribute set to LayoutKind.Auto.

Auto layout types are managed by the common language runtime. The layout of these types can change between versions of the .NET Framework, which will break COM clients that expect a specific layout. Note that if the StructLayoutAttribute attribute is not specified, the C#, Visual Basic, and C++ compilers specify the Sequential layout for value types.

Unless marked otherwise, all public nongeneric types are visible to COM; all nonpublic 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.

To fix a violation of this rule, change the value of the StructLayoutAttribute attribute to Explicit or Sequential, or make the type invisible to COM.

Do not suppress a warning from this rule.

The following example shows a type that violates the rule and a type that satisfies the rule.

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
© 2014 Microsoft