Saturday, September 01, 2007 12:00 AM
bart
Visual Basic 9.0 Feature Focus - Friend Assemblies
Welcome back to the Visual Basic 9.0 Feature Focus blog series. In this post, we'll cover Friend Assemblies, something that has been supported by C# (and the .NET Framework more generally) since Whidbey (see here). What this feature allows you to do is to expose Friend types (which are by definition visible inside the assembly in which they've been defined) to another assembly that's considered to be a "friend" of the defining assembly.
This is useful in situations where you want to split up functionality across multiple assemblies that still require tight interaction. While the outside world can only see Public types, assemblies with a friendship relation can see each other's Friend types as well. Another practical situation where this proves to be pretty useful is when writing debugger visualizers that ship with some library: you might want to make the debugger visualizer a friend of the library so that it can use internal 'Friend' features or access internal 'Friend' data that needs to be visualized, while keeping a nice separation between the library itself and the debugger visualizer (to reduce memory footprint for example).
So, how does it work? Assume you've created a Class Library project called "MyLibrary" that contains the following:
Friend Class Bar
End Class
Next, you have a Console project called "Demo" that has a reference to MyLibrary. It's pretty trivial to see that the following won't work:
Imports MyLibrary
Module Demo
Sub Main()
Dim b As New Bar()
End Sub
End Module
Indeed, the IDE tells us:
Now go back to the MyLibrary project and change the code as follows:
Imports System.Runtime.CompilerServices
<Assembly: InternalsVisibleTo("Demo")>
Friend Class Bar
End Class
Now, the code in the Demo project will compile fine since MyLibrary was so kind to expose its internals to us. The InternalsVisibleToAttribute (of which you can have more than one) takes the assembly name as its first parameter, which can be supplied in various formats: just the name (without the .dll or .exe extension) or the full name (name, version, public key token, culture).
That's it for now; just make sure you have (damn) good reasons to use this feature: don't spill friendship relations.
Happy coding!
Del.icio.us |
Digg It |
Technorati |
Blinklist |
Furl |
reddit |
DotNetKicks
Filed under: VB 9.0