Variables and Constants

A variable is a storage location within a method. In the preceding examples, both x and y are variables. You can assign values to your variables, and you can change those values programmatically.

You create a variable by declaring its type and then giving it a name. You can initialize the variable with a value when you declare it, and you can assign a new value to that variable at any time, changing the value held in the variable. Example 3-1 illustrates this.

Example 3-1. Initializing and assigning a value to a variable

using System;
using System.Collections.Generic;
using System.Text;




namespace InitializingVariables
{
 class Program
 {
    static void Main(string[] args)
    {


    int myInt = 7;
    System.Console.WriteLine("Initialized, myInt: {0}",
      myInt);


    myInt = 5;
    System.Console.WriteLine("After assignment, myInt: {0}",
      myInt);


    }
 }
}


Output:
Initialized, myInt: 7
After assignment, myInt: 5

Tip

Visual Studio creates a namespace and using directive for every program. To save space, I've omitted these from most of the code examples after this one.

Get Programming C# 3.0, 5th Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.