13.07.2015 Views

C# in Depth

C# in Depth

C# in Depth

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

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

202 CHAPTER 7 Conclud<strong>in</strong>g <strong>C#</strong> 2: the f<strong>in</strong>al featuresList<strong>in</strong>g 7.12Demonstration of friend assemblies// Compiled to Source.dllus<strong>in</strong>g System.Runtime.CompilerServices;[assembly:InternalsVisibleTo("FriendAssembly")]public class Source{<strong>in</strong>ternal static void InternalMethod(){}Grantsadditional access}public static void PublicMethod(){}// Compiled to FriendAssembly.dllpublic class Friend{static void Ma<strong>in</strong>(){Source.InternalMethod();Source.PublicMethod();}}Uses additionalaccess with<strong>in</strong>FriendAssembly// Compiled to EnemyAssembly.dllpublic class Enemy{static void Ma<strong>in</strong>(){// Source.InternalMethod();Source.PublicMethod();}}EnemyAssembly hasno special accessIn list<strong>in</strong>g 7.12 a special relationship exists between FriendAssembly.dll andSource.dll—although it only operates one way: Source.dll has no access to <strong>in</strong>ternalmembers of FriendAssembly.dll. If we were to uncomment the l<strong>in</strong>e at B, the Enemyclass would fail to compile.So, why on earth would we want to open up our well-designed assembly to certa<strong>in</strong>assemblies to start with?7.7.2 Why use InternalsVisibleTo?I can’t say I’ve ever used InternalsVisibleTo between two production assemblies.I’m not say<strong>in</strong>g there aren’t legitimate use cases for that, but I’ve not come acrossthem. However, I have used the attribute when it comes to unit test<strong>in</strong>g.There are some who say you should only test the public <strong>in</strong>terface to code. PersonallyI’m happy to test whatever I can <strong>in</strong> the simplest manner possible. Friend assembliesmake that a lot easier: suddenly it’s trivial to test code that only has <strong>in</strong>ternal access withouttak<strong>in</strong>g the dubious step of mak<strong>in</strong>g members public just for the sake of test<strong>in</strong>g, or<strong>in</strong>clud<strong>in</strong>g the test code with<strong>in</strong> the production assembly. (It does occasionally meanBAccesses publicmethod as normalLicensed to Rhona Hadida

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

Saved successfully!

Ooh no, something went wrong!