Avoid non-public fields in ComVisible value types

TypeName

AvoidNonpublicFieldsInComVisibleValueTypes

CheckId

CA1413

Category

Microsoft.Interoperability

Breaking Change

Breaking

Cause

A value type that is specifically marked as visible to COM declares a non-public instance field.

Rule Description

Non-public instance fields of COM visible value types are visible to COM clients. Review the content of the field for information that should not be exposed, or will have unintended design or security impact.

By default, all public value types are visible 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 and keep the field hidden, change the value type to a reference type or remove the ComVisibleAttribute attribute from the type.

When to Exclude Warnings

It is safe to exclude a warning from this rule if public exposure of the field is acceptable.

Example

The following example shows a type that violates the rule.

Imports System
Imports System.Runtime.InteropServices

<Assembly: ComVisibleAttribute(False)>
Namespace InteroperabilityLibrary

   <ComVisibleAttribute(True)> _ 
   Public Structure SomeStructure

      Friend SomeInteger As Integer

   End Structure

End Namespace
using System;
using System.Runtime.InteropServices;

[assembly: ComVisible(false)]
namespace InteroperabilityLibrary
{
   [ComVisible(true)]
   public struct SomeStruct
   {
      internal int SomeValue;
   }
}

Avoid static members in ComVisible types

Mark assemblies with ComVisible

See Also

Concepts

Qualifying .NET Types for Interoperation

Other Resources

Interoperating with Unmanaged Code