Contact
class:
public class Contact {
public const ushort MAX_EMAIL = 5;
public static int count;
public int ID;
public string FirstName;
public string LastName;
}
Unlike the rest of the data members, the _Email
data member has been defined with the private
keyword. The public
keyword indicates that the data member is visible outside the class, while the private
keyword indicates that the data member is only visible within the class.
By convention, you can denote a private variable by beginning its name with the underscore (_) character. This is recommended, but not mandatory.
For example, you can access the FirstName
data member through an instance of the Contact
class:
//---this is OK---
contact1.FirstName = 'Wei-Meng';
But you cannot access the _Email
data member outside the class, as the following statement demonstrates:
//---error: _Email is inaccessible---
contact1._Email = '[email protected]';
C# has four access modifiers — private
, public
, protected
, and internal
.The last two are discussed with inheritance in the next chapter.
If a data member is declared without the public
keyword, its scope (or access) is private
by default. So, _Email
can also be declared like this:
public class Contact {
public const ushort MAX_EMAIL = 5;
public static int count;
public int ID;
public string FirstName;
public string LastName;
}
Function Members
A function member contains executable code that performs work for the class. The following are examples of function members in C#:
□ Methods
□ Properties
□ Events
□ Indexers
□ User-defined operators
□ Constructors
□ Destructors
Events and indexers are covered in detail in Chapters 7 and 13.
In C#, every function must be associated with a class. A function defined with a class is known as a
[access_modifiers] return_type method_name(parameters) {
//---Method body---
}
Here's an example — the ValidateEmail()
method defined in the Contact
class:
public class Contact {
public static ushort MAX_EMAIL;
public int ID;
public string FirstName;
public string LastName;
public string Email;
}
If the method does not return a value, you need to specify the return type as void
, as the following PrintName()
method shows:
public class Contact {
public static ushort MAX_EMAIL;
public int ID;
public string FirstName;
public string LastName;
public string Email;
public Boolean ValidateEmail() {
//---implementation here---
//...
Boolean valid=true;
return valid;
}
}
You can pass values into a method using