#202 – All Fields in an Object Are Automatically Initialized

When you declare an instance of a value type without initializing it, the compiler prevents you from referencing the uninitialized variable.

            int x;

            Console.WriteLine(x);   // Compile-time error: [Use of unassigned local variable 'x']

If you declare and instantiate a reference type, the internal fields and properties are all initialized by setting all of the bits of the underlying memory for each item to 0.  This equates to:

  • Reference types = null
  • Numeric types = 0
  • Enum types = 0
  • Char type =
  • Boolean type = false

This means that value types declared inside the object are automatically initialized when the object is created.

For example, assume that we create a new Person object without calling a constructor that initializes any fields.

            Person p = new Person();

We can look at the new Person object in the debugger to see that all of its fields have been initialized.

Advertisement

About Sean
Software developer in the Twin Cities area, passionate about software development and sailing.

One Response to #202 – All Fields in an Object Are Automatically Initialized

  1. Pingback: #602 – Initializing Fields in a Class « 2,000 Things You Should Know About C#

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: