Partial class across projects is NOT ALLOWED

Well, you learn some­thing new every­day and today I found out that you can’t have a par­tial class that spans across projects in C#, i.e. if I have a par­tial class called MyClass in Pro­jec­tA:

   1: namespace ProjectA.Entities

   2: {

   3:     public partial class MyClass { }

   4: }

   5:     

I won’t be able to extend it by defin­ing anoth­er par­tial class called MyClass in Pro­jectB even if I put the new par­tial class under the same name­space. Now, that’s a bum­mer.. but when you think about it it actu­al­ly makes per­fect sense!

If par­tial class across projects were to be allowed, it would rep­re­sent a huge secu­ri­ty risk because it’d allow poten­tial­ly harm­ful code to be inject­ed into exist­ing bina­ries. Imag­ine if I had a par­tial class with pri­vate meth­ods that I don’t want to expose:

   1: public partial class MyClass

   2: {

   3:     // public methods, etc. etc.

   4:     // ...

   5:  

   6:     // no one else should be allowed to call this method!!!

   7:     private void DoSecretHandshake()

   8:     {

   9:         ...

  10:     }

  11: }

I kept these meth­ods pri­vate so oth­ers can call them, so then I com­pile, build and dis­trib­ute the bina­ries, and all of a sud­den some evil-doer is able to extend my class and do this:

   1: public partial class MyClass

   2: {

   3:     // expose the not so secret handshake

   4:     public void HackSecretHandshake()

   5:     {

   6:         DoSecretHandshake();    // mwahahahaha

   7:     }

   8: }

Now that’s no good! OK.. if some­one real­ly wants to exe­cute the DoSe­cretHand­shake method, they can always use reflec­tion to do it, but at least it won’t be so easy and indeed tempt­ing for them to try it..

Oh, and one more thing, a par­tial class is a com­pile time only piece of syn­tac­tic sug­ar and the whole thing is still com­piled into a sin­gle type, in a sin­gle project. It does how­ev­er, allow you to sep­a­rate a huge class file into mul­ti­ple files and hence mak­ing it eas­i­er to organ­ise and man­age.