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:
One approach is to use an expression. An expression combines operators to define a computation that results in a value.
Another route is to use assignment. An assignment statement requires three parts: the variable name, an equal (=) operator, and the data to be placed into the memory location of the variable.
Finally, a variable can be assigned by receiving a value from a returning method using the return keyword.
| Caution?/td> |
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.
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; } } }