}
Now there's no need for you to define private members to store the values of the properties. Instead, you just need to use the get
and set
keywords, and the compiler will automatically create the private members in which to store the properties values. If you decide to add filtering rules to the properties later, you can simply implement the set
and
get accessor of each property.
To restrict the visibility of the get
and set
accessor when using the automatic properties feature, you simply prefix the get or set accessor with the private
keyword, like this:
public string FirstName {get; private set;}
This statement sets the FirstName
property as read-only.
You might be tempted to directly convert these properties (FirstName
, LastName
, and Email
) into public data members. But if you did that and then later decided to convert these public members into properties, you would need to recompile all of the assemblies that were compiled against the old class.
Instead of initializing the individual properties of an object after it has been instantiated, it is sometimes useful to initialize them at the time of instantiation.
Using the Contact
class as the example, the following constructor initializes the ID property to 9999 every time an object is instantiated:
public class Contact {
int _ID;
public int ID {
get {
return _ID;
}
set {
if (value > 0 && value <= 9999) {
_ID = value;
} else {
_ID = 0;
};
}
}
public string FirstName { get; set; }
public string LastName { get; set; }
public string Email { get; set; }
}
The following statement proves that the constructor is called:
Contact c = new Contact();
//---prints out 9999---
Console.WriteLine(c.ID);
Constructors have the same name as the class and they do not return any values. In this example, the constructor is defined without any parameters. A constructor that takes in no parameters is called a
Contact c = new Contact();
If you do not define a default constructor in your class, an implicit default constructor is automatically created by the compiler.
You can have as many constructors as you need to, as long as each constructor'sContact
class:
public class Contact {
//...
public Contact() {
this.ID = 9999;
}
}
When you have multiple methods (constructors in this case) with the same name but different signatures, the methods are known asContact
object (see Figure 4-3).

Figure 4-3
You can create instances of the Contact class using the different constructors:
//---first constructor is called---
Contact c1 = new Contact();
//---second constructor is called---
Contact c2 = new Contact(1234);
//---third constructor is called---
Contact c3 = new Contact(1234, 'Wei-Meng', 'Lee', '[email protected]');
Suppose that the Contact
class has the following four constructors:
public class Contact {
//...