Rachael Miller
Rachael Miller

Reputation: 21

C# has-a relationship with nested class

I'm a C++ developer learning C#, and I'm in a situation where I need a class C to have two members that belong to it that represent "robots." The robots need to be able to access private members of C, and they don't need to be used anywhere else. In C++ I'd use the "friend" keyword, but I don't know what to do here. I thought about doing something like this:

class C
{
    private Member mem;
    private Robot bot;

    private class Robot
    {
        C owner;
        public void function() { //Robot needs to use owner.mem here, 
                                 //but can't because it's private}
    };
}

The trouble is that I don't know how to say that a Robot is "owned" by an instance of C, and can access its members.

Upvotes: 2

Views: 107

Answers (3)

Jeremy Thompson
Jeremy Thompson

Reputation: 65742

There are heaps of threads about this: Why does C# not provide the C++ style 'friend' keyword?

"Robot needs to use owner.mem here, but can't because it's private"

I think you want Protected with an inheritance model:

class C
{
    protected Member mem;
    protected Robot bot;
}

private class Robot : C
{
   public void function() { 
      base.mem...  // here you can use the base classes mem and bot
   };
}

Upvotes: 1

liusy182
liusy182

Reputation: 205

One way to do it is to pass the outer class's instance to the inner class's constructor as a reference.

class C
{
    private Member mem;
    private Robot bot;

    private class Robot
    {
        C owner;
        public Robot(C c) {owner = c;}
        public void function()
        { 
           // Robot can use owner.mem here
        }
    };
}

Upvotes: 2

Mohit S
Mohit S

Reputation: 14064

There's no direct equivalent of friend - the closest that's available (and it isn't very close) is InternalsVisibleToAttribute but it breaks the relationships between classes and undermines some fundamental attributes of an OO language.

The only decent solution that has occurred to me is to invent an interface, ICClass, which only exposes the public methods, and have the Factory return ICClass interfaces.

This involves a fair amount of tedium - exposing all the naturally public properties again in the interface.

Upvotes: 1

Related Questions