Team LiB
Previous Section Next Section

Variables

When a variable is declared in a statement, the compiler is told to reserve that type's amount of memory. The declaration statement does not place any value in that memory other than inheriting the value on the stack that currently occupies that memory. This is why C# requires that you initialize all variables prior to using them. After you have declared a variable type, you must initialize that variable with a value. If you do use a local variable without initializing that value, the compiler will let you know about it!

There are many ways to assign a value to a variable, including the following:

Caution 

If you do try to use a local variable without initializing that value, you will get an error at compile time. For example, if you use c:\class\Test\SimpleTester.cs, the message will be, "An object reference is required for the nonstatic field, method, or property ‘Test.SimpleTester.Test(int)’."

The following is an example of using variables.

Code Example: Using Variables
Start example

using System;

namespace Client.Chapter_1___Common_Type_System
{

      class UsingVariables
      {
            static void Main(string[] args)
              {
                    //Assignment
                  int MyInt = 12345;
                  //Using an expression
                  int MyInt2 = MyInt + 1;
                  int MyInt3;
                  //Initializing through a return value from a method
                    MyInt3 = My2ndFunction(MyInt2);
            }
            static public int My2ndFunction(int myInt2)
            {
                 myInt2 = myInt2 * 2;
                 //The value of myInt2 will be assigned to MyInt3 above
                   return myInt2;
          }
      }
}
End example

Team LiB
Previous Section Next Section