The new Operator Revisited


Now that you know more about classes and their constructors, let’s take a closer look at the new operator. As it relates to classes, the new operator has this general form:

 class-var = new class-name( );

Here, class-var is a variable of the class type being created. The class-name is the name of the class that is being instantiated. The class name followed by parentheses specifies the constructor for the class. If a class does not define its own constructor, new will use the default constructor supplied by C#. Thus, new can be used to create an object of any class type.

Since memory is finite, it is possible that new will not be able to allocate memory for an object because insufficient memory exists. If this happens, a runtime exception will occur. (You will learn how to handle this and other exceptions in Chapter 13.) For the sample programs in this book, you won’t need to worry about running out of memory, but you may need to consider this possibility in real-world programs that you write.

Using new with Value Types

At this point, you might be asking why you don’t need to use new for variables of the value types, such as int or float? In C#, a variable of a value type contains its own value. Memory to hold this value is automatically allocated by the compiler when a program is compiled. Thus, there is no need to explicitly allocate this memory using new. Conversely, a reference variable stores a reference to an object. The memory to hold this object is allocated dynamically, during execution.

Not making the fundamental types, such as int or char, into reference types greatly improves the performance of your program. When using a reference type, there is a layer of indirection that adds overhead to each object access that is avoided by a value type.

As a point of interest, it is permitted to use new with the value types, as shown here:

 int i = new int();

Doing so invokes the default constructor for type int, which initializes i to zero. For example:

 // Use new with a value type. using System; class newValue {   public static void Main() {     int i = new int(); // initialize i to zero     Console.WriteLine("The value of i is: " + i);   } }

The output from this program is

 The value of i is: 0

As the output verifies, i is initialized to zero. Remember, without the use of new, i would be uninitialized, and it would be an error to attempt to use it in the WriteLine( ) statement without explicitly giving it a value.

In general, invoking new for a value type invokes the default constructor for that type. It does not, however, dynamically allocate memory. Frankly, most programmers do not use new with the value types.




C# 2.0(c) The Complete Reference
C# 2.0: The Complete Reference (Complete Reference Series)
ISBN: 0072262095
EAN: 2147483647
Year: 2006
Pages: 300

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net