Thursday, June 26, 2008

C# Puzzle No.10 (beginner)

Is it possible that class A has direct access to private members of class B?

No, of course not. This is against encapsulation - this is the most common answer. However, there is at least one case where this actually happens and is even very important feature of the language.

So the question is : in C#, under which circumstances class A has direct access to private members of another class B?

4 comments:

andreweng said...

Easy - all inner classes have access to private members of theirs "host" classes.

Wiktor Zychla said...

that's the correct answer.

interestingly, however, I know quite a lot of people who are not aware of this feature of the language.

Unknown said...

That`s really interresting. I was so confused whan I red this, that I decided to check it by my own - and yeah: "inner" class really see private field of the host class.

By the way: the "inner" class I call "Nested" (I think this is proper name).

Anonymous said...

Yes Class A can access private variables of class B but only in following case:-

If Class A is inner class of class B as well as it should friend class of B.

//----check the code below-------------------

class B
{
private int b1 = 5;

class A : B
{
int myval()
{
return b1;
}
}
}