← back to index

S3251 — Implementations should be provided for "partial" methods

Language: C#  |  Type: CODE_SMELL  |  Severity: Minor

Tags: suspicious

Why is this an issue?

partial methods allow an increased degree of flexibility in programming a system. Hooks can be added to generated code by invoking methods that define their signature, but might not have an implementation yet. But if the implementation is still missing when the code makes it to production, the compiler silently removes the call. In the best case scenario, such calls simply represent cruft, but in the worst case they are critical, missing functionality, the loss of which will lead to unexpected results at runtime.

This rule raises an issue for partial methods for which no implementation can be found in the assembly.

How to fix it

Either supply an implementation for the partial method, or, if the hook is no longer needed, remove the partial declaration together with the calls to it. The one thing to avoid is leaving the declaration with no implementation, because the compiler then removes the calls silently and the intended behavior never runs.

Code examples

Noncompliant code example

partial class C
{
  partial void Method(); // Noncompliant: supply an implementation for this partial method

  void OtherM()
  {
    Method(); // Noncompliant: supply an implementation for the partial method, otherwise this call will be ignored
  }
}

Compliant solution

partial class C
{
  partial void Method();

  void OtherM()
  {
    Method();
  }
}

partial class C
{
  partial void Method()
  {
    // ... the implementation the call relies on ...
  }
}

Resources

Documentation