Introduction to Objects and Classes in C#, Part 2 - Private Members Only?
(Page 4 of 4 )
What about objects of that class? Can they access the members declared as private?
In short, no, the objects of this class will not see the private member, but it will have it's own copy because as we said before the class is just a template for the contents of its object. I prefer to discuss it using an example:
public
class Class2
{
private int x = 100;
}
And then I will instance 2 objects of that class inside the Main method
static void Main
(string[] args)
{
Class2 c2 = new Class2();
Class2 c3 = new Class2();
// Now Let's check if we can see
// x inside any of these objects
c2.
}
c2 and c3 are objects of type Class2() but look what happened when I typed the "." operator (which will get us all the accessible members of that class).

There is no x here because it's private to the class. You may wonder why this feature exists. Sometimes you need to hide some values inside the class (ie. you don't want other classes or objects of that class to see these values), maybe because it's complex information, or it's private to your work, or the developers that will use your class (after it's compiled) will simply not benefit if they saw these variables or methods.
You can use the access modifier keyword public while you declare your variables to specify that you want your variable to be accessed by the other classes or any objects of this class. let's revise the the x variable in Class2 and check if we can see it or not (from objects of this class or other classes).
public
class Class2
{
public int x = 100;
}
Now let's see the result:

Oh, yes we can see the x variable now because we made it public. And I will talk about Class Scope in a later article. For now, just play around with scopes. I think you'll have a lot of fun with these.
| DISCLAIMER: The content provided in this article is not warranted or guaranteed by Developer Shed, Inc. The content provided is intended for entertainment and/or educational purposes in order to introduce to the reader key ideas, concepts, and/or product reviews. As such it is incumbent upon the reader to employ real-world tactics for security and implementation of best practices. We are not liable for any negative consequences that may result from implementing any information covered in our articles or tutorials. If this is a hardware review, it is not recommended to open and/or modify your hardware. |