C# - Variables


A variable represents a numeric or string value or an object of a class. The value that the variable stores may change, but the name stays the same. A variable is one type of field. The following code is a simple example of how to declare an integer variable, assign it a value, and then assign it a new value.

    int x = 1;  // x holds the value 1
    x = 2;      // now x holds the value 2

C# variables are declared with a specific data type and a label. If your programming background is in loosely typed languages such as JScript, you are used to using the same "var" type for all variables, but in C# you must specify whether your variable is an int, a float, a byte, a short, or any of the more than 20 different data types. The type specifies, among other things, the exact amount of memory that must be allocated to store the value when the application runs. The C# language enforces certain rules when converting a variable from one type to another.

int answer = 42;
string greeting = "Hello, World!";
double bigNumber = 1e100;
System.Console.WriteLine("{0} {1} {2}", answer, greeting, bigNumber);