I am currently learning C# with the book called Beginning Visual C# 2010 and I am in the chapter that discusses different aspects and characteristics of partial methods and classes.
To quote the book:
Consider at this point why partial methods can’t have a return type. If you can answer that to your own satisfaction, you can be sure that you fully understand this topic — so that is left as an exercise for you."
This is where I get stuck. The only reason that I can think of is that when the method's return value is assigned to something in the code, it would generate an error if there is no definition implemented for the partial method.
Can someone clear this topic for me please?
Similar to a partial class, a partial method can be used as a definition in one part while another part can be the implementation. If there is no implementation of the partial method then the method and its calls are removed at compile time. Compiler compiles all parts of a partial method to a single method.
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.
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.
All parts of a partial class should be in the same namespace. Each part of a partial class should be in the same assembly or DLL, in other words you can't create a partial class in source files of a different class library project. Each part of a partial class has the same accessibility.
Because calls to them can't be eliminated from the calling code in case they are not implemented without breaking it.
Example:
partial void foo();
partial int bar();
Calling code:
...
foo(); // successfully removed if foo isn't implemented
int x = bar() * 2; // what to do here?
Console.WriteLine(x);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With