CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 12 of 12
  1. #1
    Join Date
    Sep 2004
    Location
    Tehran(Ir)
    Posts
    469

    Friend Class in C#

    Hello everybody,
    I know we have Friend Class in C++ but I wanted to know whether I can use friend class in C#,
    I figured out that its possible to use friend class in VB.NET(from http://msdn.microsoft.com/library/de...akeyFriend.asp)
    but it seems I cant use it in C# (because of this link)
    am I right?
    Thanks in advance.

  2. #2
    Join Date
    Dec 2003
    Location
    http://map.search.ch/zuerich.en.html
    Posts
    1,074

    Re: Friend Class in C#

    Do you have an example or is this just a general question?

    One other possibility to "internal" is to use inner classes which can be declared as "private" to their outer class.

  3. #3
    Join Date
    Sep 2004
    Location
    Tehran(Ir)
    Posts
    469

    Re: Friend Class in C#

    Thanks for checking my problem,
    I meant from Friend Class something there is in C++(not in VB.NET or C#.NET)
    Internal(C#.NET)==Friend(VB.NET)!=Friend(C++)
    Friend classes in C++ let just one class access another class
    Take a look at my example
    Code:
    C++
    class wheel{
    friend class car;//car can access wheel without any restriction
    friend class bus;//bus can access wheel without any restriction
     //other declarations for wheel
    };
    class car{
     //declarations for car
    };
    class bus{
     //declarations for bus
    };
    as you see I didnt use Nested Classes,(I used Composite Classes instead)
    I dont know how I can convert my C++ example to C#(without using Nested Classes)
    (if I use Nested classes I have to declare Wheel class
    in every bus or car class ...)

  4. #4
    Join Date
    Dec 2003
    Location
    http://map.search.ch/zuerich.en.html
    Posts
    1,074

    Re: Friend Class in C#

    Your given example would be solved by 'Car' and 'Bus' having a common base class and 'Wheel' being a 'nested' class of that.

    I would be interested to see a 'real-world' problem that required the C++ 'friend'.

    If 'Wheel' has any "interesting" behaviour, why break encapsulation and give "access without any restriction"?

  5. #5
    Join Date
    Jan 2002
    Location
    Scaro, UK
    Posts
    5,940

    Re: Friend Class in C#

    I can think of quite a few examples where friends are necessary in C++.

    Consider an observer class :

    Code:
    class CObserver
    {
    protected:
        virtual void OnMessage() = 0;
    } ;
    The OnMessage function will need to be called by whatever it's observing - but we don't want any other class to be able to call it.

    Therefore we use a friend :

    Code:
    class CToBeObserved;
    
    class CObserver
    {
        friend CToBeObserved;
    
    protected:
        virtual void OnMessage() = 0;
    } ;
    
    class CToBeObserved
    {
    private
        void SomethingHappens()
        {
            m_pObserver->OnMessage();
        }
    };
    Now, friends in VB.NET aren't the same as friends in C++. Friends in C++ effectively give permission for one class to have access to the protected and private methods and variables on another. Access is ONLY given to the specified classes.

    Friends in VB.NET give access to all classes in the same assembly.

    In short, there aren't any friends in .NET like the C++ friends.

    However, there are ways around the problem. I've got an article coming out showing how to do it in certain instances - e.g. this observer pattern above.

    The trick is to have an intermediate class imbetween the observer and the observee which has an event. The observer hooks into the event, which is fired by the observee calling a public member on the intermediate class.

    Not a perfect solution, but it does prevent access to the protected members on the observer class.

    Of course all of this is taken care of with events in .NET anyway - which removes much of the need for friends.

    You can declare methods in C# as being 'internal' which means they are not visible to classes outside of the containing assembly. This sort of removes the problem really.

    Darwen.
    Last edited by darwen; October 14th, 2004 at 03:17 AM.
    www.pinvoker.com - PInvoker - the .NET PInvoke Interface Exporter for C++ Dlls.

  6. #6
    Join Date
    Mar 2004
    Location
    Prague, Czech Republic, EU
    Posts
    1,701

    Re: Friend Class in C#

    There is no simple couterpart of C++'s friend in C#.

    If you need one class to access private/protected members of another and you want to avoid inheritance, than you can define the friend class as nested class. E.g. If B should have access to A's members, you can

    Code:
    public class A
    {
      public class B
      {
    ...
      }
    ...
    }
    • Make it run.
    • Make it right.
    • Make it fast.

    Don't hesitate to rate my post.

  7. #7
    Join Date
    Dec 2003
    Location
    http://map.search.ch/zuerich.en.html
    Posts
    1,074

    Re: Friend Class in C#

    Hi Darwen,

    sorry I wasn't clear, but I meant a real-world example in C# that required the C++ friend concept.

    As you say, "Of course all of this is taken care of with events in .NET anyway - which removes much of the need for friends".

    The use of interfaces also helps to remove the need.

    In your C++ example I'm not sure why OnMessage would need to be protected. In general it would only be called by the Observed but could be called directly if required. "Protected" methods are usually internal to a class. The use of "friend" here has broken encapsulation.

    Observer Pattern in C#
    Last edited by Norfy; October 14th, 2004 at 03:55 AM.

  8. #8
    Join Date
    Sep 2004
    Location
    Tehran(Ir)
    Posts
    469

    Re: Friend Class in C#

    Thanks to everybody helped me here,
    I did it like below.
    Code:
    public abstract class Vehicle
    {
    	protected class Wheel
    	{
    		// details of wheel
    	}
    	protected Wheel wheel;   
    	// vehicle details
    }
    
    public class Car : Vehicle
    {
    	// car specifics
    }
    
    public class Bus : Vehicle
    {
    	// bus specifics
    }

    I think it would be a good idea?

  9. #9
    Join Date
    Dec 2005
    Posts
    180

    Re: Friend Class in C#

    I would like to revive this topic.

    Are we saying that there is no such thing as a friend class in C#?

    I am using a dll in my C# project that I have the source code for and yet I do not want to modify the existing code. I have inherited the class and I can use my inherited class any way I want. The problem is that most of the code in the parent class has protected methods. Will using a friend somehow make it possible to access or call these protected methods?

  10. #10
    Join Date
    Jun 2008
    Posts
    2,477

    Re: Friend Class in C#

    You can always call protected methods of the base class in a derived class, you cannot call private methods of the base class.

  11. #11
    Join Date
    Mar 2004
    Location
    33°11'18.10"N 96°45'20.28"W
    Posts
    1,808

    Re: Friend Class in C#

    reflection is also an option (albeit as poor a design choice as a friend in C++).

  12. #12
    Join Date
    May 2007
    Posts
    1,546

    Re: Friend Class in C#

    Quote Originally Posted by darwen View Post
    Code:
    class CToBeObserved;
    
    class CObserver
    {
        friend CToBeObserved;
    
    protected:
        virtual void OnMessage() = 0;
    } ;
    
    class CToBeObserved
    {
    private
        void SomethingHappens()
        {
            m_pObserver->OnMessage();
        }
    };
    But this isn't the observer pattern. You're supposed to be oberving 'CToBeObserved', so the event should be on 'CToBeObserved' and that should be the only class raising 'OnMessage'. You don't require friend to make this work right, you just need to use the observer pattern correctly The usual pattern in C# is to allow subclasses to raise the event too:

    Code:
    public abstract class BaseClass
    {
        public event EventHandler<MessageSentEventArgs> MessageSent;
    
        protected virtual void RaiseMessageSent (object o, MessageSentEventArgs e)
        {
            EventHandler<MessageSentEventArgs> h = MessageSent;
            if (h != null)
                h (o, e);
        }
    }
    Now all subclasses can control when MessageSent is raised. Observers have no say in the matter, they just 'observe' when the event is raised. In your example, you're doing the opposite, you're telling each observer that the change has happened which requires the use of 'friend' to make it work.
    www.monotorrent.com For all your .NET bittorrent needs

    NOTE: My code snippets are just snippets. They demonstrate an idea which can be adapted by you to solve your problem. They are not 100% complete and fully functional solutions equipped with error handling.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured