partial method (C# Reference)
A partial method has its signature defined in one part of a partial type, and its implementation defined in another part of the type. Partial methods enable class designers to provide method hooks, similar to event handlers, that developers may decide to implement or not. If the developer does not supply an implementation, the compiler removes the signature at compile time. The following conditions apply to partial methods:
Declarations must begin with the contextual keyword partial.
Signatures in both parts of the partial type must match.
The partial
keyword isn't allowed on constructors, finalizers, overloaded operators, property declarations, or event declarations.
A partial method isn't required to have an implementation in the following cases:
It doesn't have any accessibility modifiers (including the default private).
It returns void.
It doesn't have any out parameters.
It doesn't have any of the following modifiers virtual, override, sealed, new, or extern.
Any method that doesn't conform to all those restrictions (for example, public virtual partial void
method), must provide an implementation.
The following example shows a partial method defined in two parts of a partial class:
namespace PM
{
partial class A
{
partial void OnSomethingHappened(string s);
}
// This part can be in a separate file.
partial class A
{
// Comment out this method and the program
// will still compile.
partial void OnSomethingHappened(String s)
{
Console.WriteLine("Something happened: {0}", s);
}
}
}
Partial methods can also be useful in combination with source generators. For example a regex could be defined using the following pattern:
[GeneratedRegex("(dog|cat|fish)")]
partial bool IsPetMatch(string input);
For more information, see Partial Classes and Methods.
See also
Feedback
https://aka.ms/ContentUserFeedback.
Coming soon: Throughout 2024 we will be phasing out GitHub Issues as the feedback mechanism for content and replacing it with a new feedback system. For more information see:Submit and view feedback for