In previous articles we have learnt about classes and that a class defines the item we are discussing. A customer for example does have properies, fields and methods; however it does not not define any customer. A class therefore provides a mechanism to describe an item, but does not define any real item. It is thus a blueprint.
In order to create a real customer one has to create an instance of a class and reference it through a variable name. When creating an instance of the class an object is created in memory.
The line of code below declares a variable theCustomer of data type Customer. Initially the variable is set to a value of null. A null variable means there is no real customer, however it is capable of storing a customer
Customer theCustomer;
The code below uses the new keyword to create an object in memory of type Customer. This then sets the variable theCustomer to reference the new object.
theCustomer = new Customer();
Example
The following example creates three different customer objects in memory and uses them by calling properties and methods.
namespace BrettM.Training.OO.Objects
{
using System;
/// <summary>
/// The customer class defines a business client that purchases
/// products and services from our company.
/// </summary>
class Customer
{
#region // Fields
/// <summary>
/// A field variable to hold the customers name
/// </summary>
private string _name;
#endregion
#region // Properties
/// <summary>
/// The name of the customer
/// </summary>
public string Name
{
// The get accessor to return the name field
get { return _name; }
// A set accessor to change the name field
set { _name = value; }
}
#endregion
#region // Methods
public void Print()
{
Console.WriteLine("Customer details");
Console.WriteLine("----------------");
Console.WriteLine("Name: {0}", this.Name);
Console.WriteLine();
}
#endregion
}
class Program
{
static void Main(string[] args)
{
//Create a variable of type customer
Customer theCustomer;
// Create an instance of the class
theCustomer = new Customer();
// Create the customer one object
Customer one = new Customer();
one.Name = "Mr Tom Jones";
// Create the customer two object
Customer two = new Customer();
two.Name = "Mrs Sue Smith";
// Create the customer three object
Customer three = new Customer();
three.Name = "Ms Sally Wilson";
//Print out all customer details
one.Print();
two.Print();
three.Print();
}
}
}