C#idiomatic C#
ca2257fundamentals/code-analysis/quality-rules

Code analysis

CA2257: Members defined on an interface with the 'DynamicInterfaceCastableImplementationAttribute' should be 'static'

Learn about code analysis rule CA2257: Members defined on an interface with 'DynamicInterfaceCastableImplementationAttribute' should be 'static'

CA2257 Usage enabled by default in .NET 10: As warning
Fix is breaking or non-breaking Non-breakingApplicable languages C# and Visual Basic

Cause

An interface member isn't explicitly implemented or marked static.

Rule description

Since a type that implements IDynamicInterfaceCastable may not implement a dynamic interface in metadata, calls to an instance interface member that is not an explicit implementation defined on this type are likely to fail at runtime. To avoid runtime errors, mark new interface members static.

How to fix violations

Mark the interface member static.

Example

sample · csharpdocs/fundamentals/code-analysis/quality-rules/snippets/csharp/all-rules/ca2257.cssnippet1

csharp
using System.Runtime.InteropServices;

namespace ca2257
{
    //<snippet1>
    [DynamicInterfaceCastableImplementation]
    interface IExample
    {
        // This method violates the rule.
        void BadMethod();

        // This method satisfies the rule.
        static void GoodMethod()
        {
            // ...
        }
    }
    //</snippet1>
}

When to suppress errors

Do not suppress a warning from this rule.

See also