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 −
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.
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 −
You can initialize a variable at the time of definition as −
Variables can be initialized in their declaration. The initializer consists of an equal sign followed by a constant expression as −
Some examples are −
It is a good programming practice to initialize variables properly, otherwise sometimes program may produce unexpected result.
The following example uses various types of variables −
When the above code is compiled and executed, it produces the following result −
The function Convert.ToInt32() converts the data entered by the user to int data type, because Console.ReadLine() accepts the data in string format.
But following is not a valid statement and would generate compile-time error −
| Type | Example |
|---|---|
| Integral types | sbyte, byte, short, ushort, int, uint, long, ulong, and char |
| Floating point types | float and double |
| Decimal types | decimal |
| Boolean types | true or false values, as assigned |
| Nullable types | Nullable data types |
Defining Variables
Syntax for variable definition in C# is −shellscript
csharp
csharp
Initializing Variables
Variables are initialized (assigned a value) with an equal sign followed by a constant expression. The general form of initialization is −csharp
shellscript
csharp
csharp
shellscript
Accepting Values from User
The Console class in the System namespace provides a function ReadLine()for accepting input from the user and store it into a variable. For example,csharp
Lvalue and Rvalue Expressions in C#
There are two kinds of expressions in C# −- lvalue − An expression that is an lvalue may appear as either the left-hand or right-hand side of an assignment.
- rvalue − An expression that is an rvalue may appear on the right- but not left-hand side of an assignment.
csharp
csharp

