Defining Member and Type Visibility - Private Members
(Page 3 of 6 )
The private keyword is a member access modifier. Private members are accessible only within the body of the class in which they are declared. In order to access private members outside of the class, you need to provide public methods (or properties). Here is an example to illustrate the point:
class Program
{
static void Main(string[] args)
{
Book b = new Book();
b.YearPublished = 1929;
}
}
class Book
{
private string title;
private int year_published;
public string Title
{
get { return title; }
set { title = value; }
}
public int YearPublished
{
get { return year_published; }
set
{
if (value < 1930)
{
Console.WriteLine("year cannot be less then 1930n" +
"year is reset to 1930");
year_published = 1930;
}
else
year_published = value;
}
}
}
title and year_published are declared private members, which means they can only be accessed within the Book class. In order to give users of the class access to these members, two properties have been added to the class (Title and YearPublished). These properties have been declared public to get and set the values of title and year_published. Notice that we added a condition when setting the year the book was published. In this case, we are not accepting any books published before 1930. If you declared the data public, the user of the class (being another programmer) could have changed the year in any way he/she sees fit. That could have led to data corruption.
Two important items to keep in mind about properties:
They are very useful when getting and setting private data. Properties themselves can be declared private, protected, or public. That depends on how much flexibility you need to give the user of your class.
Properties are turned into getters and setters behind the scenes. Once you compile your code, use ildasm.exe to view the content of the assembly. You notice that the class properties are changed to gets and sets. So, if you added gets and sets in addition to the properties, the compiler will give you an error message (basically you are declaring a method twice!).
Next: Protected Members >>
More C# Articles
More By Ayad Boudiab