WriteLine("Generated constructor");
OnConstructorEnd();
}
partial void OnConstructorStart();
partial void OnConstructorEnd();
}
// Handwritten.cs
using System;
partial class PartialMethodDemo
{
partial void OnConstructorEnd()
{
Console.WriteLine("Manual code");
}
}
As shown in listing 7.2, partial methods are declared just like abstract methods: by providing
the signature without any implementation but using the partial modifier.
Similarly, the actual implementations just have the partial modifier but are otherwise
like normal methods.
Calling the parameterless constructor of PartialMethodDemo would result in ???Generated
constructor??? and then ???Manual code??? being printed out. Examining the IL for
the constructor, you wouldn??™t see a call to OnConstructorStart because it no longer
exists??”there??™s no trace of it anywhere in the compiled type.
Because the method may not exist, partial methods must have a return type of
void and can??™t take out parameters. They have to be private, but they can be static
and/or generic. If the method isn??™t implemented in one of the files, the whole statement
calling it is removed, including any argument evaluations. If evaluating any of the
arguments has a side effect that you want to occur whether or not the partial method
is implemented, you should perform the evaluation separately. For instance, suppose
you have the following code:
LogEntity(LoadAndCache(id));
Here LogEntity is a partial method, and LoadAndCache loads an entity from the database
and inserts it into the cache.
Pages:
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373