C# 7.0 All-in-One For Dummies
Book image
Explore Book Buy On Amazon
C# keeps track of whether a variable has been initialized and doesn’t allow you to use an uninitialized variable. For example, the following code chunk generates a compile-time error:

public static void Main(string[] args)

{

int n;

double d;

double calculatedValue = n + d;

}

C# tracks the fact that the local variables n and d haven’t been assigned a value and doesn’t allow them to be used in the expression. Compiling this tiny program generates these compiler errors:

Use of unassigned local variable 'n'

Use of unassigned local variable 'd'

By comparison, C# provides a default constructor that initializes the data members of an object to

  • 0 for numbers
  • false for Booleans
  • null for object references
Consider the following simple program example:

using System;

namespace Test

{

public class Program

{

public static void Main(string[] args)

{

// First create an object.

MyObject localObject = new MyObject();

Console.WriteLine("localObject.n is {0}", localObject.n);

if (localObject.nextObject == null)

{

Console.WriteLine("localObject.nextObject is null");

}

// Wait for user to acknowledge the results.

Console.WriteLine("Press Enter to terminate...");

Console.Read();

}

}

public class MyObject

{

internal int n;

internal MyObject nextObject;

}

}

This program defines a class MyObject, which contains both a simple data member n of type int and a reference to an object, nextObject (both declared internal). The Main() method creates a MyObject and then displays the initial contents of n and nextObject. The output from executing the program appears this way:

localObject.n is 0

localObject.nextObject is null

Press Enter to terminate...

When the object is created, C# executes a small piece of code that the compiler provides to initialize the object and its members. Left to their own devices, the data members localObject.n and nextObject would contain random, garbage values.

The code that initializes values when they’re created is the default constructor. It constructs the class, in the sense of initializing its members. Thus C# ensures that an object starts life in a known state: all zeros, nulls, or false values, depending on type. This concept affects only data members of the class, not local variables in a method.

About This Article

This article is from the book:

About the book authors:

John Paul Mueller is a writer on programming topics like AWS, Python, Java, HTML, CSS, and JavaScript. William Sempf is a programmer and .NET evangelist. Chuck Sphar was a full-time senior technical writer for the Visual C++ product group at Microsoft.

This article can be found in the category: