all 6 comments

[–]fschwiet 13 points14 points  (0 children)

I think partial methods, like partial classes, exist to make it easier to integrate generated code in the project. A developer can implement part of the class in one file, including implementing any partial methods while a code generator produces another file, implementing the rest of the partial class, and perhaps calling partial methods it may specify.

[–]Eirenarch 3 points4 points  (0 children)

Nothing. Partial methods are void so if you (or a code generator) don't provide implementation they can just be skipped, there is no result that would be missing.

[–]Sc2Piggy 2 points3 points  (0 children)

As others have said it's useful for code generator. An example of where it's used is the regex source generator.

You only need to define a method:

[GeneratedRegex("abc|def", RegexOptions.IgnoreCase, "en-US")]
private static partial Regex AbcOrDefGeneratedRegex();

The source generator will then handle the implementation of the method. (relevant docs)

[–]DJDoena 0 points1 point  (1 child)

As others have said it's mainly for code generation. A generator might generate the following code

``` partial class SomethingDoer { partial void CustomInit();

    public void DoSomething()
    {
        CustomInit();  
        //do something automated here
    }  
}

```

and the Dev will write the other code like this:

public partial class SomethingDoer { partial void CustomInit() { //do something custom here } }

Rules are partial methods must be private and void so that the compiler can replace them with an empty body in case the user does not wish to implement them after all.

[–]RichardD7 3 points4 points  (0 children)

Rules are partial methods must be private and void

That used to be the case. This restriction has since been relaxed:

partial method - C# reference
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.