Search code examples
c#partial-methods

Partial Methods in C# Explanation


I am having a hard time understanding the usage of partial methods.

Can you provide an example that doesn't have to do with LINQ or that sort of database things?

Are partial methods the same things like when we are in the WinForms and coding behind it, if we use a method, it gets compiled, but if we don't, then it gets removed by the compiler? Is that correct?


Solution

  • When you have a partial class, you can define the signature of a method in one file and have the implementation in another. That's a partial method.

    So in one file you have:

    partial class Foo
    {
        partial void Bar();  // no implementation
    
        public void DoSomething()
        {
            // do some stuff...
            Bar();    // this will be removed if Bar isn't implemented in another partial class
            // do something else...
        }
    }
    

    And in another you have

    partial class Foo
    {
        partial void Bar()
        {
            // do something...
        }
    }
    

    This lets the first file call Bar without worrying about whether or not Bar is implemented. If Bar is not implemented somewhere, then calls to it are removed (from here):

    Partial methods enable the implementer of one part of a class to define a method, similar to an event. The implementer of the other part of the class can decide whether to implement the method or not. If the method is not implemented, then the compiler removes the method signature and all calls to the method. The calls to the method, including any results that would occur from evaluation of arguments in the calls, have no effect at run time. Therefore, any code in the partial class can freely use a partial method, even if the implementation is not supplied. No compile-time or run-time errors will result if the method is called but not implemented.

    A partial method must return void, else it'd be unsafe to remove all method calls should the method not be implemented:

    Partial method declarations must begin with the contextual keyword partial and the method must return void.

    As with partial classes, the main use is working with generated code:

    Partial methods are especially useful as a way to customize generated code. They allow for a method name and signature to be reserved, so that generated code can call the method but the developer can decide whether to implement the method. Much like partial classes, partial methods enable code created by a code generator and code created by a human developer to work together without run-time costs.

    So you might have generated code that makes a call to a partial method (defined without implementation in the generated code) and you are free to extend that partial class and implement that partial method if you want / need to.