Partial Types ASP.NET

There was a time in my web development career when I had to stop doing what I’m doing because I got stucked with a question in my mind, like anyone of us we get this nagging feeling when we have question unless it gets taken care of it will become an imaginary wall in front of us. Simple things like Partial Types.

Partial Types , what is this ? oh you’ve probably seen them a lot of times , it looks something like this :

Namespace MyFamousSoftware{
Partial Class _default { .. methods inside }

yes that partial class, from the word ‘partial’ means that your class is not quite done yet, the author sets up an extension for this class later on, so if you have a partial class you can split your class typically in multiple files, a common scenario is for a partial class to be auto-generated from some other source such as XSD’s and for that class to be augmented with additional hand-authored (you) method you do something like this:

// auto -generated
partial class Ticketing { …..}

// you
partial class Ticketing {…..}

Take note though that each time you have to declare ‘Partial’ or else you will have a nasty error for instance
you can’t do this

partial class Ticketing {….}

and do another

class ticketing {….} get it?

the participants of this class CANNOT have conflicting members ie., constructors with the same argument cannot be repeated, and Partial Classes are resolved entirely by the compiler, this means that participants (each partial class) must be available at compile time and must reside in the same assembly.

Another thing you can do also is to specify a base class on one or more partial classes just as long as there’s no disagreement in base class name.

Partial Methods (Implemented since 3.0)

A partial type may also contain Partial Methods. Partial methods lets auto-generated partial types provide customizable hooks for manual authoring (if you are the author of the object and someone’s using your object)
here is an example:

partial class PrintTicketForm {

partial void TicketAmount(decimal amount);

// you can customized further
partial class PrintTicketForm {

partial void TicketAmount (decimal amount)
   if(amount < 1)
   throw new ArgumentException('Not yet Paid');

Keep in mind that Partial methods consist of two pairs: a definition and an implementation the difference is that a definition is normally auto-generated while the implementation is hand-authored (you) , in the absense of definition the partial method is compiled away, this will allow auto-generated code to be liberal in providing hooks without having to worry about code bloat, one last thing partial method must be void and must be implicitly private.

Well, now that wasn’t too hard was it? important thing to remember is that you now know the inner workings of partial types, so in your next project you can be more creative in implementing them.