So during my last LINQ talk, I had a couple of people ask me why Partial Method were both implicitly private and must return void. So as to not slow down the presentation (we had a lot to cover) I told them I would blog an answer for them. Here it is.
So first, let's set up our sample program. We created two partial classes. One with the partial methods implemented.
namespace CSharpBlogSample
{
internal partial class Account
//Partial Methods (NOT IMPLEMENTED)
partial void OnWithdraw();
partial void OnDeposit();
}
//Partial Method (IMPLEMENTED)
partial void OnWithdraw()
Console.WriteLine("Withdrawing Money...");
partial void OnDeposit()
Console.WriteLine("Depositing Money.");
If we dig down into the IL we will see the following.
Notice how the OnDeposit and OnWithdraw methods are compiled into the dll.
If we compare that with a implementation where we do not implement the partial methods you will notice that the methods will be missing from the IL code.
This is important; if these partial methods were not implicitly private and you tried to access them from another class, you would run into trouble when they don't exist.
This is the same reason that we also need to return void.
Let's say that we wanted to call our private methods from inside our class in a "CallMyMethods" function (shown below)
void CallMyMethods()
OnDeposit();
OnWithdraw();
Since we are not implementing them in a separate partial class the methods will not be implemented inside of the CallMyMetods function.
If you were allow to return something, and were in turn using that as a return value from your CallMyMethods fuction, you would run into trouble when the partial methods were not implemented.
Hope that helps.
Happy Programming
Docwww.
Subscribe in a reader
Disclaimer The opinions expressed herein are my own personal opinions and do not represent my employer's view in anyway.