Defining Member and Type Visibility - Public Members
(Page 2 of 6 )
The public keyword is an access modifier for types and type members. In this section, however, we are discussing public for type members only. There are no restrictions on accessing public members. Any type within or outside the assembly can access public members. In the following example, x and y are declared public in the Point class:
using System;
namespace PublicMembers
{
class Program
{
static void Main(string[] args)
{
Point p = new Point();
p.x = 4;
p.y = 7;
Console.WriteLine("The point p has the following coordinates: ("
+ p.x + "," + p.y + ")");
}
}
class Point
{
public float x;
public float y;
}
}
Declaring x and y public makes them visible to other classes (and even other assemblies). In the example listed above, the Main method in the Program class manipulated x and y directly (through p.x and p.y).
Declaring field members public is not a good programming practice. One of the key concepts in object-oriented programming is information hiding. The data part of a class should always be declared private (I'll discuss this shortly). You then provide public methods that interface with the user of the class to get (or set) the private data. You might ask: why do I need that extra layer when I can access the data directly? Well, because you do not need the user of the class to corrupt the data inside the class (intentionally or unintentionally). For instance, if we declare an age variable to be public, and the user of the class changed that value to -1, then the data is corrupted and the behavior of the program is unpredictable.
On the other hand, if we declare the age variable to be private, then the users of the class do not have direct access to the age member. They can call a method or a property to change the value of age. The difference in this case is that you can add logic to the method (or property) to reject any value that does not make business sense.
Next: Private Members >>
More C# Articles
More By Ayad Boudiab