- Creating Classes
- Creating Objects
- Using Access Modifiers
- Creating Fields and Using Initializers
- Creating Methods
- Creating Properties
- Read-only Properties
- Creating Constructors
- Creating Structs
- Creating Static Members
- Creating Static Fields
- Creating Static Properties
- Creating Destructors and Handling Garbage Collection
- Overloading Methods
- Overloading Operators
- Creating Namespaces
- In Brief
Creating Constructors
We've created objects using new like this: Customer customer = new Customer();. If you're an OOP programmer, you know those parentheses after Customer are there for a reason, because when you create an object from a class, you're using the class's constructor. A constructor is a special method that has the same name as the class and returns no value. It is used to initialize the data in the object you're creating. In C#, constructors are declared this way:
[attributes] [modifiers] identifier([formal-parameter-list]) [initializer] { constructor-body }
Here are the parts of this statement:
attributes (Optional)Hold additional declarative information, as we'll see in Chapter 14.
modifiers (Optional)The allowed modifiers are new, static, virtual, abstract, override, and a valid combination of the four access modifiers.
identifierThe same as the class name.
formal-parameter-list (Optional)The optional parameters passed to the constructor. The parameters must be as accessible as the constructor itself.
initializer (Optional)Invoked before the execution of the constructor body. The initializer can be one of the following with an optional argument-list:
: base (argument-list) : this (argument-list)
constructor-bodyThe block that contains the statements that initialize the object.
For example, we can add a constructor to the Customer class so that you can initialize the customer's name when you create an object of that class. Listing 3.4 shows what that looks like. Note that the constructor has the same name as the class itself, and that we pass the constructor the name "Paul".
Listing 3.4 Creating a Constructor (ch03_04.cs)
class ch03_04 { static void Main() { Customer customer = new Customer("Paul"); System.Console.WriteLine("The customer's name is {0}", customer.Name); } } class Customer { private string name; public Customer(string name) { this.name = name; } public string Name { get { return name; } } }
Here's what you see when you run this code. Note that the name we passed to the constructor was indeed stored in the Customer object and was used:
C:\>ch03_04 The customer's name is Paul
For C++ Programmers
C# doesn't support member initialization lists in constructors that follow a colon like this: Customer (string name) : internalName(name){}. Note also that there is no C++ counterpart for calling other constructors with the this keyword.
If you don't declare a constructor, a default version without parameters is created automatically. (Note that if you do create any kind of a constructor, even a private onewhich won't allow objects to be made from a classC# will not create a default constructor.) In this default constructor, all the fields in your class are set to their default values (see Table 3.2).
You can also have one constructor call another using the this keyword, as here, where a parameterless constructor is calling the constructor we just created and passing it the name "George":
public Customer() : this("George"){}
Creating Copy Constructors
There's another kind of constructorthe copy constructor. When you copy one object to another, C# will copy the reference to the first object to the new object, which means that you now have two references to the same object. To make an actual copy, you can use a copy constructor, which is just a standard constructor that takes an object of the current class as its single parameter. For example, here's what a copy constructor for the Customer class might look like. Note that we're copying the name field to the new object:
public Customer(Customer customer) { this.name = customer.name; }
Now you can use this constructor to create copies. The copy will be a separate object, not just a reference to the original object. You can see this at work in ch03_05.cs, Listing 3.5. In that code, we create an object named customer with the name "Paul", and then copy it over to an object named customerCopy. Next, we change the name in customer to "Sam", and, to make sure customerCopy doesn't refer to the same data as customer, display the name in customerCopywhich is still "Paul".
Listing 3.5 Creating a Copy Constructor (ch03_05.cs)
class ch03_05 { static void Main() { Customer customer = new Customer("Paul"); Customer customerCopy = new Customer(customer); customer.Name = "Sam"; System.Console.WriteLine("The new customer's name is {0}", customerCopy.Name); } } class Customer { private string name; public Customer(string name) { this.name = name; } public Customer(Customer customer) { this.name = customer.name; } public string Name { get { return name; } set { name = value; } } }
Here's what you see when you run ch03_05.cs. As you can see, customerCopy does not refer to the same object as customer:
C:\>ch03_05 The new customer's name is Paul