13.07.2015 Views

C# in Depth

C# in Depth

C# in Depth

SHOW MORE
SHOW LESS
  • No tags were found...

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Partial types189List<strong>in</strong>g 7.2A partial method called from a constructor// Generated.csus<strong>in</strong>g System;partial class PartialMethodDemo{public PartialMethodDemo(){OnConstructorStart();Console.WriteL<strong>in</strong>e("Generated constructor");OnConstructorEnd();}}partial void OnConstructorStart();partial void OnConstructorEnd();// Handwritten.csus<strong>in</strong>g System;partial class PartialMethodDemo{partial void OnConstructorEnd(){Console.WriteL<strong>in</strong>e("Manual code");}}As shown <strong>in</strong> list<strong>in</strong>g 7.2, partial methods are declared just like abstract methods: by provid<strong>in</strong>gthe signature without any implementation but us<strong>in</strong>g the partial modifier.Similarly, the actual implementations just have the partial modifier but are otherwiselike normal methods.Call<strong>in</strong>g the parameterless constructor of PartialMethodDemo would result <strong>in</strong> “Generatedconstructor” and then “Manual code” be<strong>in</strong>g pr<strong>in</strong>ted out. Exam<strong>in</strong><strong>in</strong>g the IL forthe constructor, you wouldn’t see a call to OnConstructorStart because it no longerexists—there’s no trace of it anywhere <strong>in</strong> the compiled type.Because the method may not exist, partial methods must have a return type ofvoid and can’t take out parameters. They have to be private, but they can be staticand/or generic. If the method isn’t implemented <strong>in</strong> one of the files, the whole statementcall<strong>in</strong>g it is removed, <strong>in</strong>clud<strong>in</strong>g any argument evaluations. If evaluat<strong>in</strong>g any of thearguments has a side effect that you want to occur whether or not the partial methodis implemented, you should perform the evaluation separately. For <strong>in</strong>stance, supposeyou have the follow<strong>in</strong>g code:LogEntity(LoadAndCache(id));Here LogEntity is a partial method, and LoadAndCache loads an entity from the databaseand <strong>in</strong>serts it <strong>in</strong>to the cache. You might want to use this <strong>in</strong>stead:MyEntity entity = LoadAndCache(id);LogEntity(entity);That way, the entity is loaded and cached regardless of whether an implementationhas been provided for LogEntity. Of course, if the entity can be loaded equallyLicensed to Rhona Hadida

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!