#36 – Variable Initialization and Definite Assignment

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;
Advertisement

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

4 Responses to #36 – Variable Initialization and Definite Assignment

  1. Pingback: #341 – Defining and Using Local Variables « 2,000 Things You Should Know About C#

  2. kai zhou says:

    If the initialization when declaring a variable is only to avoid the compile time error, I think it’s better not initialize it to avoid logic bugs.

    I know it’s a good practice well accepted, and I also followed it for a long time. But as I review this practice, I cannot find a strong reason to avoid the compile time error but at the risk of introducing logic bugs.

  3. kai zhou says:

    I’m talking about:

    “It’s considered good practice to initialize a variable when you declare it. “

  4. CuriousLearner says:

    The default value of the variable ‘i’ (all integers have a default value of 0) here is 0. So why cant the compiler use that value to perform addition and return of value of variable ‘j’ to be 1?

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: