10/08/2008

The Private Access Modifier Can Do That?

If you look up accessibility levels on the MSDN web site, it will tell you that the accessibility of the private access modifier is limited to the containing type. I ran into an instance that showed me the direct meaning of this statement. The scenario I had was this: I wanted to have the ability to make an object read only. That is the original object however, if a clone was made then the object could be modified again because it wasn’t the original object. Of course this is a simple task, we get to go back and visit my good friend ICloneable.

So we start off by making our data object, putting in the ability to mark it read only and giving it the ability to clone itself.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
public class Lion : ICloneable
{
public Lion()
{

}

public Lion(string name)
{
this.Name = name;
}

private bool _isReadOnly;

public bool IsReadOnly
{
get { return _isReadOnly; }
}

private string _name;

public string Name
{
get { return _name; }
set
{
if (_isReadOnly)
throw new ReadOnlyException("This object is read only");
_name = value;
}
}

public void MakeReadOnly()
{
_isReadOnly = true;
}

#region ICloneable Members

public Lion Clone()
{
Lion result = (Lion)((ICloneable)this).Clone();
result._isReadOnly = false;
return result;
}

object ICloneable.Clone()
{
return this.MemberwiseClone();
}

#endregion
}

Take a look at line #43 above. During the cloning process, you can set the private variable _isReadOnly on the newly cloned object!

For some reason, I was under the impression that any and all private fields and methods were private to that instance of the object. This would mean that all private members of the cloned object would have to be called in the cloned object. To my surprise, this is not the case at all. After changing the _isReadOnly field of the cloned object, the object that was cloned will still remain read only. The cloned object will remain editable until the MakeReadOnly() method is called on it.

Conclusion

All fields and methods with the private access modifier are exposed at any time as long as you are in the containing type. The implications of this are that if you clone an object you will have access to the private members of the newly created object. This can be extremely useful, especially if you want a specific action to be performed on a cloned object but you don’t want to explicitly call that action publicly.

Hope this helps!

View Comments