Creating Objects in C-Sharp
(Page 1 of 4 )
In this second part of a four-part series on classes and objects in C#, you'll learn how to create objects, use static members, and much more. This article is excerpted from chapter four of the book
Programming C# 3.0, fifth edition, written by Jesse Liberty and Donald Xie (O'Reilly, 2008; ISBN: 0596527438). Copyright © 2008 O'Reilly Media, Inc. All rights reserved. Used with permission from the publisher. Available from booksellers or direct from O'Reilly Media.
Creating Objects
In Chapter 3, I drew a distinction between value types and reference types. The primitive C# types (int, char, etc.) are value types and are created on the stack. Objects, however, are reference types and are created on the heap, using the keywordnew, as in the following:
Time t = new Time();
t doesn’t actually contain the value for theTime object; it contains the address of that (unnamed) object that is created on the heap.titself is just a reference to that object.
VB 6 programmers take note: although there is a performance penalty in using the VB 6 keywordsDimandNew on the same line, in C#, this penalty has been removed. Thus, in C#, there is no drawback to using thenewkeyword when declaring an object variable.
Constructors
In Example 4-1, notice that the statement that creates the Time object looks as though it is invoking a method:
Time t = new Time();
In fact, a method is invoked whenever you instantiate an object. This method is called a constructor, and you must either define one as part of your class definition, or let the CLR provide one on your behalf. The job of a constructor is to create the object specified by a class and to put it into a valid state. Before the constructor runs, the object is undifferentiated memory; after the constructor completes, the memory holds a valid instance of the classtype.
TheTimeclass of Example 4-1 doesn’t define a constructor. If a constructor is not declared, the compiler provides one for you. The default constructor creates the object, but takes no other action.
Member variables are initialized to innocuous values (integers to 0, strings to null, etc.).* Table 4-2 lists the default values assigned to primitive types.
Table 4-2. Primitive types and their default values
Type numeric (int, long, etc.) bool | Default value 0 false |
char enum | '\0' (null) 0 |
reference | null |
Typically, you’ll want to define your own constructor and provide it with arguments so that the constructor can set the initial state for your object. In Example 4-1, assume that you want to pass in the current year, month, date, and so forth so that the object is created with meaningful data.
To define a constructor, you declare a method whose name is the same as the class in which it is declared. Constructors have no return type and are typically declared public. If there are arguments to pass, you define an argument list just as you would for any other method. Example 4-3 declares a constructor for theTimeclass that accepts a single argument, an object of typeDateTime.
Example 4-3. Declaring a constructor
#region Using directives
using System;
using System.Collections.Generic;
using System.Text;
#endregion
namespace DeclaringConstructor
{
public class Time
{
// private member variables
int Year;
int Month;
int Date;
int Hour;
int Minute;
int Second;
// public accessor methods
public void DisplayCurrentTime()
{
System.Console.WriteLine( "{0}/{1}/{2} {3}:{4}:{5}",
Month, Date, Year, Hour, Minute, Second );
}
// constructor
public Time( System.DateTime dt )
{
Year = dt.Year;
Month = dt.Month;
Date = dt.Day;
Hour = dt.Hour;
Minute = dt.Minute;
Second = dt.Second;
}
}
public class Tester
{
static void Main()
{
System.DateTime currentTime = System.DateTime.Now;
Time t = new Time( currentTime );
t.DisplayCurrentTime();
}
}
}
Output:
11/16/2007 16:21:40
In this example, the constructor takes aDateTime object and initializes all the member variables based on values in that object. When the constructor finishes, theTimeobject exists and the values have been initialized. WhenDisplayCurrentTime()is called inMain(), the values are displayed.
Try commenting out one of the assignments and running the program again. You’ll find that the member variable is initialized by the compiler to0. Integer member variables are set to0if you don’t otherwise assign them. Remember, value types (e.g., integers) can’t be uninitialized; if you don’t tell the constructor what to do, it will try for something innocuous.
In Example 4-3, theDateTimeobject is created in theMain()method ofTester. This object, supplied by theSystemlibrary, offers a number of public values—Year,Month,Day,Hour,Minute, andSecond—that correspond directly to the private member variables of theTimeobject. In addition, theDateTimeobject offers a static member property,Now, which is a reference to an instance of aDateTimeobject initialized with the current time.
Examine the highlighted line inMain(), where theDateTimeobject is created by calling the static propertyNow.Nowcreates aDateTimevalue which, in this case, gets copied to thecurrentTimevariable on the stack.
ThecurrentTimevariable is passed as a parameter to theTimeconstructor. TheTimeconstructor parameter,dt, is a copy of theDateTimeobject.
Next: Initializers >>
More C# Articles
More By O'Reilly Media