What is a 'friend' class?

D

darrel

In the context of VB.net, when/why would one use a 'friend class'. I'm
finding lots of references to friend classes on google, but not a simle
definition of what they actually are.

Actually, if there is a nice overview of the different types of classes
(public, private, shared, friend, etc.) and how they differ on a broad
level, I'd certainly like to read it. I'm at the point where I'm a 'decent
hack' and .net but I'm missing some broader overall concepts that I need to
get a better grasp on.

-Darrel
 
K

Kevin Spencer

One minor correction, Steve: A Friend class, method, or other entity is
visible to any classes in any assemblies within the same application, not
just within the same assembly.

--
HTH,
Kevin Spencer
..Net Developer
Microsoft MVP
I get paid good money to
solve puzzles for a living
 
D

darrel

A Friend class is only visible to other classes within the same
assembly.
Steve, Kevin...thank you both!

-Darrel
 
K

Karl Seguin

The tutorial provided by steve is a good start, but to answer one of your
questions specifically, that is when you would use such a modifier. The C#
term is "internal" which to me is more accurate since the scope of anything
marked "friend" is only inside the assembly itself. One typical use of
this is for security purposes - your code might do something a little iffy,
which is fine as long as its confined to your own code. If your class is
public instead of friend, someone could subclass your code and make
dangerous use of your iffy code.

For example, FxCop raises the following error:
Methods used as event handlers should not be externally visible

Rule Description
Event-handling methods should not be exposed unless absolutely necessary. An
event handler that invokes the exposed method can be added to any event as
long as the handler and event signatures match. Events can potentially be
raised by any code, and are often raised by highly trusted system code in
response to user actions such as clicking a button. Adding a security check
to an event-handling method does not prevent code from registering an event
handler that invokes the method.

How to Fix Violations
To fix a violation of this rule, make the method private or internal.

As you can see, the solution is to mark such methods as private (which could
likely be too restrictive) or internal (which typically fits the bill).

Karl
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top