Page

C# - Variables

A variable is nothing but a name given to a storage area that our programs can manipulate. Each variable in C# has a specific type, which determines the size and layout of the variable's memory the range of values that can be stored within that memory and the set of operations that can be applied to the variable.
The basic value types provided in C# can be categorized as −
TypeExample
Integral typessbyte, byte, short, ushort, int, uint, long, ulong, and char
Floating point typesfloat and double
Decimal typesdecimal
Boolean typestrue or false values, as assigned
Nullable typesNullable data types
C# also allows defining other value types of variable such as enum and reference types of variables such as class, which we will cover in subsequent chapters.

Defining Variables

Syntax for variable definition in C# is −
 ;
Here, data_type must be a valid C# data type including char, int, float, double, or any user-defined data type, and variable_list may consist of one or more identifier names separated by commas.
Some valid variable definitions are shown here −
int i, j, k;
char c, ch;
float f, salary;
double d;
You can initialize a variable at the time of definition as −
int i = 100;

Initializing Variables

Variables are initialized (assigned a value) with an equal sign followed by a constant expression. The general form of initialization is −
variable_name = value;
Variables can be initialized in their declaration. The initializer consists of an 
equal sign followed by a constant expression as −
  = value;
Some examples are −
int d = 3, f = 5;    /* initializing d and f. */
byte z = 22;         /* initializes z. */
double pi = 3.14159; /* declares an approximation of pi. */
char x = 'x';        /* the variable x has the value 'x'. */
It is a good programming practice to initialize variables properly, otherwise sometimes program may produce unexpected result.