Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

please illustrate a problem that partial methods solve

Tags:

c#

I'm still not really getting the upside of partial methods. Can anyone illustrate a problem that partial methods are ideally suited to solve?

like image 602
jcollum Avatar asked Nov 30 '22 18:11

jcollum


1 Answers

From Partial Class and Methods (C# Programming Guide) on the MSDN:

A partial class or struct may contain a partial method. One part of the class contains the signature of the method. An optional implementation may be defined in the same part or another part. If the implementation is not supplied, then the method and all calls to the method are removed at compile time.

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.

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.

In my opinion, I would recommend to avoid using these unless you have a particular, specific need for them.

like image 188
Rich Avatar answered Dec 16 '22 23:12

Rich