title | description | ms.date | ms.topic | f1_keywords | helpviewer_keywords | author | ms.author | manager | ms.subservice | monikerRange | ||||
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
CA1407: Avoid static members in COM visible types |
A type that is specifically marked as visible to Component Object Model (COM) contains a public static method. |
11/04/2016 |
reference |
|
|
mikejo5000 |
mikejo |
mijacobs |
code-analysis |
vs-2019 |
Item | Value |
---|---|
RuleId | CA1407 |
Category | Microsoft.Interoperability |
Breaking change | Non-breaking |
A type that is specifically marked as visible to Component Object Model (COM) contains a public``static
method.
COM does not support static
methods.
This rule ignores property and event accessors, operator overloading methods, or methods that are marked by using either the xref:System.Runtime.InteropServices.ComRegisterFunctionAttribute?displayProperty=fullName attribute or the xref:System.Runtime.InteropServices.ComUnregisterFunctionAttribute?displayProperty=fullName attribute.
By default, the following are visible to COM: assemblies, public types, public instance members in public types, and all members of public value types.
For this rule to occur, an assembly-level xref:System.Runtime.InteropServices.ComVisibleAttribute must be set to false
and the class- xref:System.Runtime.InteropServices.ComVisibleAttribute must be set to true
, as the following code shows.
using System;
using System.Runtime.InteropServices;
[assembly: ComVisible(false)]
namespace Samples
{
[ComVisible(true)]
public class MyClass
{
public static void DoSomething()
{
}
}
}
To fix a violation of this rule, change the design to use an instance method that provides the same functionality as the static
method.
It is safe to suppress a warning from this rule if a COM client does not require access to the functionality that is provided by the static
method.
The following example shows a static
method that violates this rule.
:::code language="csharp" source="../snippets/csharp/VS_Snippets_CodeAnalysis/FxCop.Interoperability.ComVisibleStaticMembersViolation/cs/FxCop.Interoperability.ComVisibleStaticMembersViolation.cs" id="Snippet1":::
In this example, the Book.FromPages method cannot be called from COM.
To fix the violation in the previous example, you could change the method to an instance method, but that does not make sense in this instance. A better solution is to explicitly apply ComVisible(false)
to the method to make it clear to other developers that the method cannot be seen from COM.
The following example applies xref:System.Runtime.InteropServices.ComRegisterFunctionAttribute to the method.
:::code language="csharp" source="../snippets/csharp/VS_Snippets_CodeAnalysis/FxCop.Interoperability.ComVisibleStaticMembersFixed/cs/FxCop.Interoperability.ComVisibleStaticMembersFixed.cs" id="Snippet1":::
CA1017: Mark assemblies with ComVisibleAttribute
CA1406: Avoid Int64 arguments for Visual Basic 6 clients