Tuesday, 16 December 2014

"Private" member access within same class

Sometime we are so busy "doing stufff" and miss the most basic concepts.

See the following code (LinqPad):


The key factor to consider here whether the code is going to compile. Actually it compiles and executes without any exceptions.

If you look closely you will see "friend.i.Dump()" and "friend.j.Dump()". This might be a cause for concern. This is because "i" and "j" are private members and how come we can call "f.i" in the "Add" method.

The "private" modifier indicates that the members can only be accessed within the same class. So in this particular case we are "inside" the "Friend" class and members are visible. Reference is here.

In order to prevent this confusion, simply use a property. That is simple and universally understood.

No comments:

Post a Comment