#36 – Variable Initialization

Variables must be assigned a value before they can be used.  You can declare a variable without initializing it, but attempting to reference the value of the variable before you’ve given it a value will result in a compiler error.

 int i;
 int j = i + 1;   // Error: Use of unassigned local variable 'i'

This requirement of definite assignment before use means that you are never able to reference an unassigned variable in C#.

It’s considered good practice to initialize a variable when you declare it.  This applies to both built-in types and custom types.

When you initialize a variable, the object that it references is said to be instantiated.

 Person p = new Person();
 int i = 0;

About Sean
Software developer in the Twin Cities area, passionate about .NET technologies. Equally passionate about my own personal projects related to family history and preservation of family stories and photos.

One Response to #36 – Variable Initialization

  1. Pingback: #341 – Defining and Using Local Variables « 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

Follow

Get every new post delivered to your Inbox.

Join 43 other followers